Java web--Image Upload

Source: Internet
Author: User

First, the JSP:

1<body>2     <!--Note: 1. type= "File"; 2.method= "POST"; 3.enctype= "Multipart/form-data" -3<form action= "Uploadservlet" method= "post" enctype= "Multipart/form-data" >4Employee Number: <input type= "text" name= "Empno"/><br/><br/>5Employee Name: <input type= "text" name= "ename"/><br/><br/>6 Department:7<select name= "Deptno" >8<option value= "Ten" > Sales Department </option>9<option value= ">it" department </option>Ten<option value= "> HR Department </option> One</select><br/><br/> ACAPTCHA: <input type= "text" name= "code" ><a href= "Javascript:changecode ()" > Change </a><br/><br/> -          -              theHead: <input type= "file" name= "UploadFile" > - -<br/><br/> -          +<input type= "reset" value= "reset"/> -<input type= "Submit" value= "register"/> +</form> A</body> at

Second, the Import Tool pack

Iii. obtaining data in a servlet

 Packageservlet;ImportJava.io.File;Importjava.io.IOException;Importjava.util.Date;ImportJava.util.Iterator;Importjava.util.List;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.commons.fileupload.FileItem;Importorg.apache.commons.fileupload.FileUploadException;Importorg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;/*** Servlet Implementation class Uploadservlet*/@WebServlet ("/uploadservlet") Public classUploadservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doPost (request, response); }        protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//determine if the upload form is a multipart/form-data type        if(servletfileupload.ismultipartcontent (Request)) {Try {                //1. Create Diskfileitemfactory object, set buffer size and temp file directoryDiskfileitemfactory factory =Newdiskfileitemfactory (); //System.out.println (System.getproperty ("Java.io.tmpdir"));//Default Temp Folder//2. Create the Servletfileupload object and set the size limit for the upload file. Servletfileupload SFU =Newservletfileupload (Factory); Sfu.setsizemax (10*1024*1024);//cannot exceed 10M 1024byte = 1kb 1024kb=1m 1024M = 1G in bytesSfu.setheaderencoding ("Utf-8"); //3. Call the Servletfileupload.parserequest method to parse the request object and get a list object that holds all the uploaded content. List<fileitem> fileitemlist =sfu.parserequest (Request); Iterator<FileItem> Fileitems =Fileitemlist.iterator (); //4. Iterate through the list, each iteration of a Fileitem object, calling its Isformfield method to determine whether the file is uploaded                 while(Fileitems.hasnext ()) {Fileitem Fileitem=Fileitems.next (); //Normal TABLE element                    if(Fileitem.isformfield ()) {String name= Fileitem.getfieldname ();//Name property valueString value = fileitem.getstring ("Utf-8");//name corresponds to value valuesSystem.out.println (Name+ " = "+value); }                    //<input type= "File" > The elements of the uploaded file                    Else{String FileName= Fileitem.getname ();//file nameSYSTEM.OUT.PRINTLN ("Original filename:" + filename);//koala.jpgString suffix= Filename.substring (Filename.lastindexof ('. '))); System.out.println ("Extension:" + suffix);//. jpg//new file name (unique)String NewFileName =NewDate (). GetTime () +suffix; System.out.println ("New file Name:" + newfilename);//image\1478509873038.jpg//5. Call the Write () method of Fileitem, writing to the fileFile File =NewFile (Request.getservletcontext (). Getrealpath ("image") + "\ \" +newfilename);                        System.out.println (File.getabsolutepath ());                                                Fileitem.write (file); //6. Call Fileitem's Delete () method to delete the temporary fileFileitem.delete (); /** Note When storing to database * 1. Save the source file name Koala.jpg * 2. Save relative Path Image/1478509873038.jpg **/Request.setattribute ("Image_name", FileName); Request.setattribute ("Image_path", "image/" +newfilename); Request.getrequestdispatcher ("/upload.jsp"). Forward (request, response); }                }                            } Catch(fileuploadexception e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); }                                }    }}

Java web--Image Upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.