JSPs can be used with HTML form tags to allow users to upload files to the Server. The uploaded file can be either a text file or an image file or any Document. We use Servlets to process file uploads, and the files used Are:
- Upload.jsp: File Upload form.
- Message.jsp: jump page after successful Upload.
- Uploadservlet.java: Upload processing Servlet.
- jar files that need to be introduced: commons-fileupload-1.3.2, commons-io-2.5.jar.
The structure is as follows:
1. Create a file upload form:
The following HTML code creates a file upload Form. The following points need to be noted:
- The form method property should be set to POST and cannot be used with the GET method .
- The form enctype property should be set to Multipart/form-data.
- The form Action property should be set to the Servlet file that handles file uploads on the Back-end server . The following example uses the uploadservlet Servlet to upload a file.
- To upload a single file, you should use a single <input .../> tag with the attribute type= "file". To allow multiple files to be uploaded, include multiple input tags with different name attribute values . The input label has a different name attribute Value. The browser associates a browse button for each input Tag.
The upload.jsp file code is as Follows:
<%@ page language="Java"Contenttype="text/html; Charset=utf-8"pageencoding="UTF-8"%><! DOCTYPE HTML Public"-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD">"Content-type"Content="text/html; Charset=utf-8"><title> File Upload instance </title><form method= "post" action= "/tomcattest/uploadservlet" enctype= "multipart/form-data" >Select a file:<input type="file"Name="UploadFile"/> <br/><br/> <input type="Submit"Value="Upload"/></form></body>
2, Write the background Servlet:
Here is the source code for uploadservlet, which is the same as processing the file upload, before we make sure that the dependency package has been introduced into the Project's web-inf/lib directory:
- The following instance is dependent on FileUpload, so be sure to have the latest version of the commons-fileupload.x.x.jar file in your classpath, which can be Commons.apache.org/proper/commons-fileupload/download.
- FileUpload relies on Commons IO, so be sure to have the latest version of the commons-io-x.x.jar file in your Classpath. Can be downloaded from http://commons.apache.org/proper/commons-io/.
You can directly download the two dependent packages available on this site:
- Commons-fileupload-1.3.2.jar
- Commons-io-2.5.jar
The source code for Uploadservlet is as Follows:
package com.runoob.test;import java.io.file;import Java.io.ioexception;import java.io.printwriter;import java.util.List; Import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.HttpServletResponse; Import Org.apache.commons.fileupload.fileitem;import org.apache.commons.fileupload.disk.DiskFileItemFactory; Import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class Uploadservlet*/@WebServlet ("/uploadservlet") public classUploadservlet 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, IOException { //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 = 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.jspGetservletcontext (). Getrequestdispatcher ("/message.jsp"). forward (request, response); }}
The message.jsp file code is as Follows:
<%@ page language="Java"Contenttype="text/html; Charset=utf-8"pageencoding="UTF-8"%><! DOCTYPE HTML Public"-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD">"Content-type"Content="text/html; Charset=utf-8"><title> File Upload results </title>${message}
3. Compiling and running the Servlet
Compile the above Servlet Uploadservlet and create the required entries in the Web. XML file as Follows:
<?xml version="1.0"encoding="UTF-8"? ><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://java.sun.com/xml/ns/javaee"Xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemalocation="Http://java.sun.com/xml/ns/javaeehttp//java.sun.com/xml/ns/javaee/web-app_2_5.xsd "Id="webapp_id"version="2.5"> <servlet> <display-name>UploadServlet</display-name><servlet-name>UploadServlet</servlet-name> <servlet-class>com.runoob.test.uploadservlet </servlet-class></servlet><servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/ Tomcattest/uploadservlet</url-pattern> </servlet-mapping></web-app>
JSP Learning Note (iv): File upload