In web application development, file upload and download functions are very commonly used functions. The following article will introduce you to a detailed explanation of JavaWeb file upload and download examples.
For file upload, the browser submits the file to the server in the form of a stream during the upload process. It is more troublesome if you directly use Servlet to obtain the input stream of the uploaded file and then parse the request parameters in it. Therefore, it is generally chosen to use the common-fileupload, the file upload component of the apache open source tool. The jar package of the common-fileupload upload component can be downloaded on the apache official website. common-fileupload depends on the common-io package, so you also need to download this package.
1. File upload
jsp upload page
The following precautions are required to upload components
form form: method=”post” enctype=”multipart/form-data”
Belongs to the domain: input type=”file” name=”file” size=”50”
These two points are done and displayed as follows
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Upload test</title></head><body><form action="DealwithUpload.jsp" method="post" enctype="multipart/form-data"><input type="file" name="file" size="50"><input type="submit" name="submit" value="submit"></form></body></html>
WEB.xml configuration upload path
The upload path can also be written directly in the code, but the configuration is convenient here to modify it.
<context-param><description>Location to store uploaded file</description><param-name>file-upload</param-name><param-value>e://temp//</param-value></context-param>
Handle uploaded JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ page import="org.apache.commons.fileupload.FileItem,org.apache.commons.fileupload.disk.DiskFileItemFactory, org.apache.commons.fileupload.servlet.ServletFileUpload" %><%@ page import="java.io.File" %><%@ page import="java.util.Iterator" %><%@ page import="java.util.List" %><%File file ;int maxFileSize = 5000 * 1024;int maxMemSize = 5000 * 1024;ServletContext context = pageContext.getServletContext();String filePath = context.getInitParameter("file-upload");//Get the upload path in the configuration file String contentType = request.getContentType();//Return the MIME type of the request body if ((contentType.contains("multipart/form-data"))) {DiskFileItemFactory factory = new DiskFileItemFactory();//Create a hard disk-based FileItemfactory.setSizeThreshold(maxMemSize);//Set the maximum cache factory.setRepository(new File("e://temp//"));//Set the temporary directory used for uploading ServletFileUpload upload = new ServletFileUpload(factory);//Create a file upload processor upload.setSizeMax(maxFileSize);//Set the maximum size of file upload, unit Btry{List fileItems = upload.parseRequest(request);// parse composite form data and return a collection of fileItems, so that multiple files can be uploaded at once Iterator i = fileItems.iterator();out.println("<html>");out.println("<head>");out.println("<title>JSP File upload</title>");out.println("</head>");out.println("<body>");// traverse the uploaded file while ( i.hasNext () ){FileItem fi = (FileItem)i.next();if ( !fi.isFormField () )//If it is the upload file type, because the form may be mixed with other input types {String fieldName = fi.getFieldName();//Return fileString fileName = fi.getName();//Return the upload file name, here you can check whether the uploaded file suffix is legal, use String's endWith() to boolean isInMemory = fi.isInMemory();//Long sizeInBytes = fi.getSize();//Return the file size//Start write to the file, the file name is customizable if( fileName.lastIndexOf("//") >= 0 ){file = new File( filePath ,fileName.substring( fileName.lastIndexOf("//"))) ;}else{file = new File( filePath ,fileName.substring(fileName.lastIndexOf("//")+1)) ;}fi.write( file ) ;out.println("Uploaded Filename: " + filePath +fileName + "<br>");}}out.println("</body>");out.println("</html>");}catch(Exception ex) {System.out.println(ex);}}else{out.println("<html>");out.println("<head>");out.println("<title>Servlet upload</title>");out.println("</head>");out.println("<body>");out.println("<p>No file uploaded</p>");out.println("</body>");out.println("</html>");}%>2. File download
The file download reference to Gushan Canglang's blog, which was written in detail and was used directly.
The basic idea of downloading is: first traverse all files in the download directory, then display them on the page, the client makes a request to download, and the server responds to the download.
List all files in the download directory:
public class ListFileServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//Get the directory for uploading the file String uploadFilePath = this.getServletContext().getRealPath("/WEB-INF/upload");//Storage the file name to be downloaded Map<String,String> fileNameMap = new HashMap<String,String>();//Recursively traverse all files and directories in the filepath directory, and store the file name of the file in the map collection listfile(new File(uploadFilePath),fileNameMap);//File can represent either a file or a directory//Send the Map collection to the listfile.jsp page for display request.setAttribute("fileNameMap", fileNameMap);request.getRequestDispatcher("/listfile.jsp").forward(request, response);}/*** @Method: listfile* @Description: Recursively traverse all files in the specified directory* @param file means a file, and also a file directory* @param map Map collection that stores file names*/public void listfile(File file,Map<String,String> map){//If the file represents not a file, but a directory if(!file.isFile()){//List all files and directories in this directory File files[] = file.listFiles();//Transtraverse files[] array for(File f : files){//Recursive listfile(f,map);}}else{/*** Process the file name. The uploaded file is renamed in the form of uuid_file name. Remove the uuid_part of the file name file.getName().indexOf("_") to retrieve the location of the "_" character in the string. If the file name is similar to: 9349249849-88343-8344_A_Fan_Davi.avi, then file.getName().substring(file.getName().indexOf("_")+1) can get the A_Fan_Davi.avi part*/String realName = file.getName().substring(file.getName().indexOf("_")+1);//file.getName() gets the original name of the file. This name is unique, so it can be used as a key. RealName is the processed name. It may be repeated map.put(file.getName(), realName);}} public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}Here I briefly talk about the listfile method in ListFileServlet. The listfile method is used to list all files in the directory. The listfile method uses recursion. In actual development, we will definitely create a table in the database, which will store the uploaded file name and the specific storage directory of the file. We can know the specific storage directory of the file by querying the table, and there is no need to use recursion operations. This example is because the database does not store the uploaded file name and the specific storage location of the file, and the storage location of the uploaded file is used to break up the storage, so recursion is needed. During recursion, the obtained file name is stored in the Map collection passed from outside to the listfile method, so we can ensure that all files are stored in the same Map collection.
Configure ListFileServlet in Web.xml file
<servlet><servlet-name>ListFileServlet</servlet-name><servlet-class>me.gacl.web.controller.ListFileServlet</servlet-class></servlet><servlet-mapping><servlet-name>ListFileServlet</servlet-name><url-pattern>/servlet/ListFileServlet</url-pattern></servlet-mapping>
The listfile.jsp page displaying the downloaded file is as follows:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE HTML><html><head><title>Download file display page</title></head><body><!-- traverse Map collection--><c:forEach var="me" items="${fileNameMap}"><c:url value="/servlet/DownLoadServlet" var="downurl"><c:param name="filename" value="${me.key}"></c:param></c:url>${me.value}<a href="${downurl}">Download</a><br/></c:forEach></body></html>Implement file download
package me.gacl.web.controller;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.net.URLEncoder;import javax.servlet.Servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DownloadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//Get the file name to be downloaded String fileName = request.getParameter("filename"); //23239283-92489-Avatar.avifileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");//The uploaded files are saved in the subdirectory of the /WEB-INF/upload directory String fileSaveRootPath=this.getServletContext().getRealPath("/WEB-INF/upload");//Find out the directory where the file is located by the file name String path = findFileSavePathByFileName(fileName,fileSaveRootPath);//Get the file to be downloaded File file = new File(path + "//" + fileName);//If the file does not exist if(!file.exists()){request.setAttribute("message", "The resource you want to download has been deleted!!");request.getRequestDispatcher("/message.jsp").forward(request, response);return;}//Processing file name String realname = fileName.substring(fileName.indexOf("_")+1);//Set the response header to control the browser to download the file response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));//Read the file to be downloaded and save it to the file input stream FileInputStream in = new FileInputStream(path + "//" + fileName);//Create the output stream OutputStream out = response.getOutputStream();//Create the buffer byte buffer[] = new byte[1024];int len = 0;//Loop read the contents of the input stream into the buffer while((len=in.read(buffer))>0){//Output the contents of the buffer to the browser to realize the file download out.write(buffer, 0, len);}//Close the file input stream in.close();//Close the output stream out.close();}/*** @Method: findFileSavePathByFileName* @Description: Find the path of the file to be downloaded through the file name and storage root directory* @param filename filename to download* @param saveRootPath The root directory for uploading the file, that is, /WEB-INF/upload directory* @return the storage directory of the file to be downloaded*/ public String findFileSavePathByFileName(String filename,String saveRootPath){int hashcode = filename.hashCode();int dir1 = hashcode&0xf; //0--15int dir2 = (hashcode&0xf0)>>4; //0-15String dir = saveRootPath + "//" + dir1 + "//" + dir2; //upload/2/3 upload/3/5File file = new File(dir);if(!file.exists()){//Create directory file.mkdirs();}return dir;}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}Configuring DownloadServlet in Web.xml file
<servlet><servlet-name>DownLoadServlet</servlet-name><servlet-class>me.gacl.web.controller.DownLoadServlet</servlet-class></servlet><servlet-mapping><servlet-name>DownLoadServlet</servlet-name><url-pattern>/servlet/DownLoadServlet</url-pattern></servlet-mapping>
The above is the relevant knowledge about uploading and downloading JavaWeb files introduced to you by the editor. I hope it will be helpful to you.