Jsp + Servlet implement file upload/download file upload (1), servlet File Upload
The file upload and download functions are essential and useful for Java Web.
This article uses the famous File Upload Component under Apache.
Org. apache. commons. fileupload implementation
Next we will first write the first file to upload based on the materials we have recently seen and our own attempts. In the future, we will gradually download, display the file list, and upload information persistence.
Put it bluntly and directly add the code
Step 1,Reference the jar package and set the upload directory
Commons-fileupload-1.3.1.jar
Commons-io-2.4.jar
Upload Directory: WEB-INF/tempFiles and WEB-INF/uploadFiles
Step 2,Compile a JSP page
<% @ Page contentType = "text/html; charset = UTF-8 "language =" java "%> <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%>
Step 3,Compile Servlet to process the core of File Upload
Package servlet; import org. apache. commons. fileupload. fileItem; import org. apache. commons. fileupload. fileUploadBase; import org. apache. commons. fileupload. fileUploadException; import org. apache. commons. fileupload. progressListener; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; import javax. servlet. servletException; impor T javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. util. calendar; import java. util. iterator; import java. util. list; import java. util. UUID;/*** process File Upload ** @ Uthor xusucheng * @ create 2017-12-27 **/@ WebServlet ("/UploadServlet") public class UploadServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest request, response) throws ServletException, IOException {// set the basic path for file upload String savePath = this. getServletContext (). getRealPath ("/WEB-INF/uploadFiles"); // set the temporary file path String tempPath = this. getServletContext (). getRe AlPath ("/WEB-INF/tempFiles"); File tempFile = new File (tempPath); if (! TempFile. exists () {tempFile. mkdir () ;}// defines the error message String errorMessage = ""; // creates the file items factory DiskFileItemFactory factory = new DiskFileItemFactory (); // sets the buffer size factory. setSizeThreshold (1024*100); // set the temporary file path factory. setRepository (tempFile); // create a file upload processor ServletFileUpload upload = new ServletFileUpload (factory); // listen to the file upload progress ProgressListener progressListener = new ProgressListener () {public void upda Te (long pBytesRead, long pContentLength, int pItems) {System. out. println ("reading file:" + pItems); if (pContentLength =-1) {System. out. println ("read:" + pBytesRead + "remaining 0");} else {System. out. println ("total file size:" + pContentLength + "read:" + pBytesRead) ;}}; upload. setProgressListener (progressListener); // solves the Chinese garbled upload of the uploaded file name. setHeaderEncoding ("UTF-8"); // determines whether the submitted data is the data of the upload form if (! ServletFileUpload. isMultipartContent (request) {// obtain the data return in the traditional way;} // set the maximum size of a single file to be uploaded. Currently, the value is set to 1024*1024 bytes, that is, 1 MB upload. setFileSizeMax (1024*1024); // sets the maximum size of the total number of uploaded files. The maximum value is the sum of the maximum size of multiple files uploaded at the same time. Currently, it is set to 10 MB upload. setSizeMax (1024*1024*10); try {// use the ServletFileUpload parser to parse the uploaded data. The parsed result returns a List <FileItem> set, each FileItem corresponds to the input item List <FileItem> items = upload. parseRequest (request); Iterator <FileItem> ite Rator = items. iterator (); while (iterator. hasNext () {FileItem item = iterator. next (); // determine whether the file submitted by jsp is if (item. isFormField () {errorMessage = "Submit a file! "; Break;} else {// file name String fileName = item. getName (); if (fileName = null | fileName. trim () = "") {System. out. println ("the file name is blank! ");} // Handle the file name with path problem submitted by different browsers fileName = fileName. substring (fileName. lastIndexOf ("\") + 1); // file extension String fileExtension = fileName. substring (fileName. lastIndexOf (". ") + 1); // determine whether the extension is legal if (! ValidExtension (fileExtension) {errorMessage = "the uploaded file is invalid! "; Item. delete (); break;} // get the file input stream InputStream in = item. getInputStream (); // get the name of the saved file String saveFileName = createFileName (fileName); // get the file storage path String realFilePath = createRealFilePath (savePath, saveFileName ); // create a file output stream FileOutputStream out = new FileOutputStream (realFilePath); // create a buffer byte buffer [] = new byte [1024]; int len = 0; while (len = in. read (buffer)> 0) {// write file out. write (buffer, 0, Len);} // close the input stream in. close (); // close the output stream out. close (); // Delete the temporary file TODO item. delete (); // Save the uploaded file information to the TODO} catch (FileUploadBase. fileSizeLimitExceededException e) {e. printStackTrace (); request. setAttribute ("errorMessage", "a single file exceeds the maximum !!! "); Request. getRequestDispatcher ("pages/upload. jsp "). forward (request, response); return;} catch (FileUploadBase. sizeLimitExceededException e) {e. printStackTrace (); request. setAttribute ("errorMessage", "the total size of the uploaded file exceeds the maximum value !!! "); Request. getRequestDispatcher ("pages/upload. jsp "). forward (request, response); return;} catch (FileUploadException e) {e. printStackTrace (); request. setAttribute ("errorMessage", "File Upload Failed !!! "); Request. getRequestDispatcher ("pages/upload. jsp "). forward (request, response); return;} request. setAttribute ("errorMessage", errorMessage); request. getRequestDispatcher ("pages/upload. jsp "). forward (request, response) ;}@ Override protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);} private Boolean validExtension (String fileExtension) {String [] exts = {"jpg", "txt", "doc", "pdf"}; for (int I = 0; I <exts. length; I ++) {if (fileExtension. equals (exts [I]) {return true ;}} return false;} private String createFileName (String fileName) {return UUID. randomUUID (). toString () + "_" + fileName;}/*** generate a real file path based on the basic path and file name, basic path \ year \ month \ fileName ** @ param basePath * @ param fileName * @ retu Rn */private String createRealFilePath (String basePath, String fileName) {Calendar today = Calendar ar. getInstance (); String year = String. valueOf (today. get (Calendar. YEAR); String month = String. valueOf (today. get (Calendar. MONTH) + 1); String upPath = basePath + File. separator + year + File. separator + month + File. separator; File uploadFolder = new File (upPath); if (! UploadFolder. exists () {uploadFolder. mkdirs ();} String realFilePath = upPath + fileName; return realFilePath ;}}
Step 4,Test
Http: // localhost: 8080/helloweb/pages/upload. jsp
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.