1. Write the following code in INDEX.JSP
<form method="Post"action="Demo3"Enctype="Multipart/form-data">Select a file:<input type="file"Name="UploadFile"/> <br/><br/> <input type="Submit"Value="Upload"/></form>
2. Create the ServletDemo3 class in SRC
Import Org.apache.commons.fileupload.FileItem;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import org.apache.commons.fileupload.servlet.servletfileupload;//This three package for the normal package outside of the additional need to download imports
Public classServletDemo3 extends HttpServlet {Private StaticFinalLongSerialversionuid =1L; //upload file storage directory Private StaticFinal String upload_directory ="Upload"; //Upload Configuration Private StaticFinalintMemory_threshold =1024x768*1024x768*3;//3MB Private StaticFinalintMax_file_size =1024x768*1024x768* +;//40MB Private StaticFinalintMax_request_size =1024x768*1024x768* -;//50MB /** * Upload data and save files*/ protected voidDoPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IO Exception {//detect if uploading is multimedia if(!servletfileupload.ismultipartcontent (Request)) { //if not then stopPrintWriter writer =Response.getwriter (); Writer.println ("Error: The form must contain Enctype=multipart/form-data"); Writer.flush (); return; } //Configure upload ParametersDiskfileitemfactory factory =Newdiskfileitemfactory (); //set the memory threshold-after which a temporary file is generated and stored in the temp directoryFactory.setsizethreshold (Memory_threshold); //Set temporary storage directoryFactory.setrepository (NewFile (System.getproperty ("Java.io.tmpdir"))); Servletfileupload Upload=Newservletfileupload (Factory); //set maximum file upload valueUpload.setfilesizemax (max_file_size); //Set maximum request value (include file and form data)Upload.setsizemax (max_request_size); //Chinese processingUpload.setheaderencoding ("UTF-8"); //constructing a temporary path to store uploaded files//This path is relative to the currently applied directoryString Uploadpath = Request.getservletcontext (). Getrealpath ("./") + File.separator +upload_directory; //If the directory does not exist, createFile Uploaddir =NewFile (Uploadpath); if(!uploaddir.exists ()) {Uploaddir.mkdir (); } Try { //parse the requested content extract file data@SuppressWarnings ("unchecked") List<FileItem> Formitems =upload.parserequest (Request); if(Formitems! =NULL&& formitems.size () >0) { //iterate represents single data for(Fileitem item:formitems) {//working with fields that are not in a form if(!Item.isformfield ()) {String FileName=NewFile (Item.getname ()). GetName (); String FilePath= Uploadpath + File.separator +FileName; File StoreFile=NewFile (FilePath); //upload path to the console output fileSystem. out. println (FilePath); //save file to hard diskItem.write (StoreFile); Request.setattribute ("message", "File Upload successful!"); } } } } Catch(Exception ex) {Request.setattribute ("message", "error message:"+ex.getmessage ()); } //Jump to message.jspRequest.getservletcontext (). Getrequestdispatcher ("/message.jsp"). Forward (request, response); } }
3. configuring Files in Web-inf
<servlet> <servlet-name>servletDemo3</servlet-name> <servlet-class> com.neunb.servlet.servletdemo3</servlet-class> </servlet> <servlet-mapping > <servlet-name>servletDemo3</servlet-name> <url-pattern>/demo3</url-pattern > </servlet-mapping>
4. Create message.jsp Display upload results
"content-type" content= " text/html; Charset=utf-8 "> <title> File Upload results </title>
5. Upload file Run resultsJSP implements file upload using servlet