In Javaweb, uploading and downloading is a common function. For file upload, the browser passes the file to the server in the process of uploading the file in a streaming process. Generally, the commons-fileupload package is used to implement the upload function. Because commons-fileupload depends on the commons-io package, you need to download these two packages commons-fileupload-1.2.1.jar and commons-io-1.3.2.jar.
1. Build an environment
Create a web project and import the package into the project lib
2. Implement file upload
(The first method of uploading)
Create a new upload.jsp page
<%@ 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"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>upload file</title></head><body> <!--The <%=request.getContextPath()%> here represents the absolute path to the project, which means that no matter where you copy the project to in the future, it will find the exact path--> <form action="<%=request.getContextPath()%>/uploadServlet" enctype="multipart/form-data" method="post"> <span>Select file: </span><input type="file" name="file1"> <input type="submit" value="upload"> </form></body></html>
Create a new Servlet that handles file upload
package com.load;import java.io.File;import java.io.IOException;import java.util.List;import javax.servlet.ServletContext;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.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;@WebServlet("/uploadServlet")public class uploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public uploadServlet() { super(); } /* In the fileupload package, the complex form elements in the HTTP request are regarded as a FileItem object; * The FileItem object must be parsed by the parseRequest() method in the ServletFileUpload class* (that is, the wrapped HttpServletRequest object), that is, the specific text form and upload file are separated* */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Use isMultipartContent() method: analyze whether there are requests on files in the request, boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart){ //Create a settable disk node factory DiskFileItemFactory factory = new DiskFileItemFactory(); //Get the context information of the request ServletContext servletContext = request.getServletContext(); //Cache directory, each server-specific directory File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); //Set the server's cache directory factory.setRepository(repository); //The creation of ServletFileUpload object needs to depend on FileItemFactory //The factory saves the obtained upload file FileItem object to the server hard disk, that is, the DiskFileItem object. ServletFileUpload upload = new ServletFileUpload(factory); try { // parse the HttpServletRequest object after being wrapped, which is to separate text forms and upload files (http requests will be wrapped as HttpServletRequest) List<FileItem> items = upload.parseRequest(request); for(FileItem item:items){ String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); //Instantiate a file//request.getRealPath(get the real path) File file = new File(request.getRealPath("/")+"/loads"+fileName.substring(fileName.lastIndexOf("//")+1,fileName.length())); item.write(file); } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}(The second upload method)
Create a new Jsp page (same as above, just the path is changed)
<%@ 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"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>upload file</title></head><body> <!--The <%=request.getContextPath()%> here represents the absolute path to the project, which means that no matter where you copy the project in the future, it will find the exact path--> <form action="<%=request.getContextPath()%>/uploadservlet1" enctype="multipart/form-data" method="post"> <span>Select file: </span><input type="file" name="file1"> <input type="submit" value="upload"> </form></body></html>
Create Servlet to handle upload
package com.load;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.ServletException;import javax.servlet.annotation.MultipartConfig;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;@WebServlet("/uploadservlet1")@MultipartConfig(location="")public class uploadservlet1 extends HttpServlet { private static final long serialVersionUID = 1L; public uploadservlet1() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("utf-8"); //Get upload file and read the file Part part = request.getPart("file1"); //Define a variable to receive the file name String filename = null; //Content-Disposition: It is to provide a default file name when the user wants to save the requested content as a file //Content-Disposition: Tell the browser to open the file by downloading for (String content: part.getHeader("content-disposition").split(";")) { System.out.println(content); //Get the file name if (content.trim().startsWith("filename")) { //Intercept the file name filename = content.substring( content.indexOf('=') + 1).trim().replace("/"", ""); } } //OutputStream out = null; //Input Stream InputStream filecontent = null; //File.separator Gets the system's dividing line and other data out = new FileOutputStream(new File("e:/loads" + File.separator + filename)); int read; //Get an input stream filecontent = part.getInputStream(); final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } System.out.println("New file " + filename + " created at " + "/loads"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}(The third method of uploading)
The jspSmartUpload package is used here to upload and download. The author believes that this kind of upload and download is relatively simple, but it seems that many people don’t use it and don’t understand it.
Create HTML page
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Upload file</title></head><body> <p> </p> <p align="center">Upload file selection</p> <form method="post" Action="../DouploadServlet" enctype="multipart/form-data"> <table align="center"> <tr><td><div align="center"> 1.<input type="file" name="file1" > </div></td></tr> <tr><td><div align="center"> 2.<input type="file" name="file2" > </div></td></tr> <tr><td><div align="center"> 3.<input type="file" name="file3" > </div></td></tr> <tr><td><div align="center"> <input type="submit" name="Submit" value="upload him"> </div></td></tr> </table> </form></body></html>
Create a Servlet to process upload files
package com.load;import java.io.IOException;import java.io.PrintWriter;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 javax.servlet.jsp.JspFactory;import javax.servlet.jsp.PageContext;import com.jspsmart.upload.File;import com.jspsmart.upload.SmartUpload;import com.jspsmart.upload.SmartUploadException;@WebServlet("/DouploadServlet")public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public DownloadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // Create a new smart upload object SmartUpload su = new SmartUpload(); /* * PageContext pageContext; HttpSession session; ServletContext application; ServletConfig config; JspWriter out; Object page = this; HttpServletRequest request, HttpServletResponse response Where page object, request and response have been instantiated, while the other 5 objects that are not instantiated are instantiated in the following way pageContext = jspxFactory.getPageContext(this, request, response, null, true, 8192, true); */ //Get the context environment through the Jsp factory class PageContext pagecontext = JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true); //Upload initialize su.initialize(pagecontext); //Upload file try { su.upload(); //Save the upload file to the specified directory int count = su.save("/share"); out.println(count+"file upload successfully!<br>"+su.toString()); } catch (SmartUploadException e) { e.printStackTrace(); } //Extract upload file information one by one for(int i=0;i<su.getFiles().getCount();i++){ File file = su.getFiles().getFile(i); //If the file does not exist if(file.isMissing()) continue; //Show current file information out.println("<table border=1>"); out.println("<tr><td>Form item name(FieldName)</td></td>"+file.getFieldName()+"</td></tr>"); out.println("<tr><td>File length</td><td>"+file.getSize()+"</td></tr>"); out.println("<tr><td>File name</td><td>"+file.getFileName()+"</td></tr>"); out.println("<tr><td>File name</td><td>"+file.getFileName()+"</td></tr>"); out.println("<tr><td>File extension</td><td>"+file.getFileExt()+"</td></tr>"); out.println("<tr><td>File full name</td><td>"+file.getFilePathName()+"</td></tr>"); out.println("</table><br>"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }} Note: The code int count = su.save("/share"); means that you need to create a folder first, so you can first create one in Webcontent, then undeploy the project, and then redeploy it in, a folder will be created on the run side!
Or you can directly find the path to run and create the share folder.
3. Realize file download
(First file download)
Note: This code directly accesses the Servlet class
package com.load;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;//Directly use Http://localhost:8080/Test1/download to download, but this is flawed. If there is Chinese in the download file name, it will become garbled! @WebServlet("/download")public class download extends HttpServlet { private static final long serialVersionUID = 1L; public download() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Location","Chinese.txt"); response.setHeader("Content-Disposition", "attachment; filename=" + "Account.txt"); OutputStream outputStream = response.getOutputStream(); InputStream inputStream = new FileInputStream("E:/loads"+"/Account.txt"); byte[] buffer = new byte[1024]; int i = -1; while ((i = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, i); } outputStream.flush(); outputStream.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}(The second download method)
Create a new jsp page and select download
<%@ 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"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Download</title></head><body> <a href="../DoDownloadServlet?filename=hehe.txt">Click to download</a></body></html>
Create a Servlet class to download (note: if the file name of this download is Chinese, it will still cause garbled code)
package com.load;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URLEncoder;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 javax.servlet.jsp.JspFactory;import javax.servlet.jsp.PageContext;import org.hsqldb.lib.StringUtil;import com.jspsmart.upload.SmartUpload;import com.jspsmart.upload.SmartUploadException;@WebServlet("/DoDownloadServlet")public class DoDownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public DoDownloadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the name of the downloaded file//String filename = request.getParameter("filename"); //String filename = new String(FileName.getBytes("iso8859-1"),"UTF-8"); //Create a new SmartUpload object SmartUpload su = new SmartUpload(); PageContext pagecontext = JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true); //Upload initialization su.initialize(pagecontext); //Set prohibit opening of the file su.setContentDisposition(null); //Download file try { su.downloadFile("/listener/"+filename); } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}(The third method of downloading)
The same jsp page code as above will not be repeated here.
Create a new Serlvet class to implement the download function (note: even if the file name is a Chinese name, there will be no garbled problems!)
package com.load;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URLEncoder;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 javax.servlet.jsp.JspFactory;import javax.servlet.jsp.PageContext;import org.hsqldb.lib.StringUtil;import com.jspsmart.upload.SmartUpload;import com.jspsmart.upload.SmartUploadException;@WebServlet("/DoDownloadServlet")public class DoDownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public DoDownloadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get file name String path1 = request.getParameter("filename"); //Get path name String path = request.getSession().getServletContext().getRealPath("/listener/"+path1); // path is a file spliced based on the log path and file name. String filename = file.getName(); try { //Judge whether it is IE11 Boolean flag= request.getHeader("User-Agent").indexOf("like Gecko")>0; //IE11 User-Agent string: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko //IE6~IE10 version User-Agent string: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.0; Trident/6.0) if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") >0||flag){ filename = URLEncoder.encode(filename, "UTF-8");//IE browser}else { //First remove the spaces in the file name, and then convert the encoding format to utf-8 to ensure that there is no garbled code. //This file name is used for the file name automatically displayed in the browser's download box filename = new String(filename.replaceAll(" ", "").getBytes("UTF-8"), "ISO8859-1"); //firefox browser//firefox browser User-Agent string: //Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0 } InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer; buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" +filename); response.addHeader("Content-Length", "" + file.length()); OutputStream os = response.getOutputStream(); response.setContentType("application/octet-stream"); os.write(buffer);// Output file os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println(filename); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.