Apache file upload and file download case in detail

  • 2020-06-12 11:37:40
  • OfStack

Write a case of Apache file upload and file download: for future study

web. xml configuration is as follows:


<span style="font-family:SimSun;font-size:14px;"><?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> 
 <display-name>FileUploadAndDownload</display-name> 
 <welcome-file-list> 
  <welcome-file>index.html</welcome-file> 
  <welcome-file>index.htm</welcome-file> 
  <welcome-file>index.jsp</welcome-file> 
  <welcome-file>default.html</welcome-file> 
  <welcome-file>default.htm</welcome-file> 
  <welcome-file>default.jsp</welcome-file> 
 </welcome-file-list> 
  <!--  Upload the configuration  --> 
  <servlet> 
    <servlet-name>uploadHandleServlet</servlet-name> 
    <servlet-class>com.zeng.controller.UploadHandleServlet</servlet-class> 
  </servlet>  
  <servlet-mapping> 
    <servlet-name>uploadHandleServlet</servlet-name> 
    <url-pattern>/upload/uploadHandleServlet</url-pattern> 
  </servlet-mapping> 
  <servlet> 
    <servlet-name>listFileServlet</servlet-name> 
    <servlet-class>com.zeng.controller.ListFileServlet</servlet-class> 
  </servlet>  
  <servlet-mapping> 
    <servlet-name>listFileServlet</servlet-name> 
    <url-pattern>/listFileServlet</url-pattern> 
  </servlet-mapping> 
  <servlet> 
    <servlet-name>downLoadServlet</servlet-name> 
    <servlet-class>com.zeng.controller.DownLoadServlet</servlet-class> 
  </servlet>  
  <servlet-mapping> 
    <servlet-name>downLoadServlet</servlet-name> 
    <url-pattern>/download/downLoadServlet</url-pattern> 
  </servlet-mapping> 
</web-app></span> 

2. upload. jsp file


<span style="font-family:SimSun;font-size:14px;"><%@page language="java" pageEncoding="UTF-8"%> 
<!DOCTYPE HTML> 
<html> 
 <head> 
  <title> File upload </title> 
 </head> 
  
 <body> 
 <!--  
  ${pageContext.request.contextPath} :  The effect is to fetch the deployed application name  
   disadvantages : The operation is inconvenient, other tools cannot explain correctly ${pageContext.request.contextPath}  
   
   if Servlet Is the configuration path of  /upload/uploadHandleServlet 
  action Jump path is :    ${pageContext.request.contextPath}/upload/uploadHandleServlet 
   
   When uploading a file , Must be  
  1.enctype="multipart/form-data" 
  2.method=post 
  --> 
  <form action="${pageContext.request.contextPath}/upload/uploadHandleServlet" enctype="multipart/form-data" method="post"> 
     Upload user: <input type="text" name="username"><br/> 
     Upload a file 1 : <input type="file" name="file1"><br/> 
     Upload a file 2 : <input type="file" name="file2"><br/> 
    <input type="submit" value=" submit "> 
  </form> 
 </body> 
</html></span> 

3.message.jsp


<span style="font-family:SimSun;font-size:14px;"><%@page language="java" pageEncoding="UTF-8"%> 
<!DOCTYPE HTML> 
<html> 
 <head> 
  <title> Message prompt </title> 
 </head> 
 <body> 
    ${message} 
 </body> 
</html></span> 

4.UploadHandleServlet.java


<span style="font-family:SimSun;font-size:14px;">package com.zeng.controller; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.List; 
import java.util.UUID; 
import javax.servlet.ServletException; 
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.FileUploadBase; 
import org.apache.commons.fileupload.ProgressListener; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
/** 
* @ClassName: UploadHandleServlet 
* @Description: TODO( Here with 1 A sentence describes what this class does ) 
*/  
public class UploadHandleServlet extends HttpServlet { 
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
        // Get the saved directory of uploaded files, and store the uploaded files in WEB-INF Under the directory, the external direct access is not allowed to ensure the security of uploaded files  
        String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); 
        // The temporary files generated during upload are saved in the directory  
        String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); 
        File tmpFile = new File(tempPath); 
        if (!tmpFile.exists()) { 
          // Create a temporary directory  
          tmpFile.mkdir(); 
        } 
        // Message prompt  
        String message = ""; 
        try{ 
          // use Apache Steps to handle file upload:  
          //1 , create, 1 a DiskFileItemFactory The factory  
          DiskFileItemFactory factory = new DiskFileItemFactory(); 
          // Set the size of the buffer for the factory. When the uploaded file size exceeds the size of the buffer, it will be generated 1 Three temporary files are stored in the specified temporary directory.  
          factory.setSizeThreshold(1024*100);// Set the size of the buffer to 100KB If not specified, the size of the buffer defaults to 10KB 
          // Sets the save directory for temporary files that are generated when uploading  
          factory.setRepository(tmpFile); 
          //2 , create, 1 File upload parser  
          ServletFileUpload upload = new ServletFileUpload(factory); 
          // Monitor file upload progress  
          upload.setProgressListener(new ProgressListener(){ 
            public void update(long pBytesRead, long pContentLength, int arg2) { 
              System.out.println(" The file size is: " + pContentLength + ", Currently processed: " + pBytesRead + ",arg2: " + arg2); 
              /** 
               *  The file size is: 14608, Currently processed: 4096 
                 The file size is: 14608, Currently processed: 7367 
                 The file size is: 14608, Currently processed: 11419 
                 The file size is: 14608, Currently processed: 14608 
               */ 
            } 
          }); 
           // Solve the Chinese code of the upload file name  
          upload.setHeaderEncoding("UTF-8");  
          //3 Determine whether the submitted data is the data of the upload form  
          if(!ServletFileUpload.isMultipartContent(request)){ 
            // Get the data the traditional way  
            return; 
          } 
          // Sets the maximum size for uploading a single file, currently set to 1024*1024*20 Bytes, which means 20MB 
          upload.setFileSizeMax(1024*1024*20); 
          // Set the maximum amount of files that can be uploaded = The sum of the maximum sizes of multiple files uploaded simultaneously is currently set to 100MB 
          upload.setSizeMax(1024*1024*100); 
          //4 , the use of ServletFileUpload The parser parses the uploaded data, and the parsed result returns 1 a List<FileItem> Each set, 1 a FileItem The corresponding 1 a Form The input to the form  
          List<FileItem> list = upload.parseRequest(request); 
          for(FileItem item : list){ 
            // if fileitem Encapsulates the data for common input items  
            if(item.isFormField()){ 
              String name = item.getFieldName(); 
              // Solve the Chinese scrambling problem of common input data  
              String value = item.getString("UTF-8"); 
              System.out.println(name + "=" + value); 
            }else{// if fileitem Encapsulates the upload file  
              // Get the name of the uploaded file,  
              String filename = item.getName(); 
              System.out.println(filename); 
              if(filename==null || filename.trim().equals("")){ 
                continue; 
              } 
              // Note: Different browsers submit file names that are not 1 Similarly, some browsers submit file names with paths, such as:  c:\a\b\1.txt , while some are simply file names, such as: 1.txt 
              // Process the path part of the filename of the uploaded file to get, leaving the filename part alone  
              filename = filename.substring(filename.lastIndexOf("\\")+1); 
              // Gets the extension for the uploaded file  
              String fileExtName = filename.substring(filename.lastIndexOf(".")+1); 
              // If you need to limit the type of file you upload, you can determine whether the uploaded file type is valid by the file extension  
              System.out.println(" The extension of the uploaded file is: "+fileExtName); 
              // To obtain item Input stream to the uploaded file  
              InputStream in = item.getInputStream(); 
              // Gets the name of the file to save  
              String saveFilename = makeFileName(filename); 
              // The file name :d507ef2e-aca9-4908-a8b9-c1d1c6a2f4d9_ Japanese 2 Level grammar corpus ( recommended ).doc 
              //System.out.println("saveFilename: " + saveFilename); 
              // Get the directory where files are saved  
              String realSavePath = makePath(saveFilename, savePath); 
              // create 1 A file output stream  
              FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename); 
              // create 1 A buffer  
              byte buffer[] = new byte[1024]; 
              // An identifier that determines whether the data in the input stream has been read  
              int len = 0; 
              // The loop reads the input stream into the buffer, (len=in.read(buffer))>0 It means in There's data in there  
              while((len=in.read(buffer))>0){ 
                // use FileOutputStream The output stream writes the buffer's data to the specified directory (savePath + "\\" + filename) among  
                out.write(buffer, 0, len); 
              } 
              // Close the input stream  
              in.close(); 
              // Close the output stream  
              out.close(); 
              // Deletes temporary files generated when processing file uploads  
              //item.delete(); 
              message = " File upload successful! "; 
            } 
          } 
        }catch (FileUploadBase.FileSizeLimitExceededException e) { 
          e.printStackTrace(); 
          request.setAttribute("message", " Single file exceeds maximum value!! "); 
          request.getRequestDispatcher("../message.jsp").forward(request, response); 
          return; 
        }catch (FileUploadBase.SizeLimitExceededException e) { 
          e.printStackTrace(); 
          request.setAttribute("message", " The total size of the uploaded file exceeds the maximum limit!! "); 
          request.getRequestDispatcher("../message.jsp").forward(request, response); 
          return; 
        }catch (Exception e) { 
          message= " File upload failed! "; 
          e.printStackTrace(); 
        } 
        request.setAttribute("message",message); 
        // Access path  /FileUploadAndDownload/upload/upload.jsp 
        // Jump path  /FileUploadAndDownload/upload/listFileServlet 
        // Forwarding path  /FileUploadAndDownload/message.jsp 
        // The current path is at /FileUploadAndDownload/upload/ Under the , Want to jump /FileUploadAndDownload/ Under the , Must be ../message.jsp 
        //----- if  message.jsp Is in the /FileUploadAndDownload/upload/ Under the , Use it directly message.jsp 
        request.getRequestDispatcher("../message.jsp").forward(request, response); 
  } 
  /** 
  * @Method: makeFileName 
  * @Description:  Generate the file name of the upload file with the following file name: uuid+"_"+ The original name of the file  
  * @param filename  The original name of the file  
  * @return uuid+"_"+ The original name of the file  
  */  
  private String makeFileName(String filename){ //2.jpg 
    // To prevent file overwrite, generate for upload files 1 A wei 1 The name of the file  
    return UUID.randomUUID().toString() + "_" + filename; 
  } 
  /** 
   *  In order to prevent 1 There are too many files under 5 directories to use hash The algorithm scatters the storage  
  * @Method: makePath 
  * @param filename  Filename from which to generate the storage directory  
  * @param savePath  File storage path  
  * @return  New storage directory  
  */  
  private String makePath(String filename,String savePath){ 
    // To get the file name hashCode Theta is equal to theta filename The address of the string object in memory  
    int hashcode = filename.hashCode(); 
    int dir1 = hashcode&0xf; //0--15 
    int dir2 = (hashcode&0xf0)>>4; //0-15 
    // Construct a new save directory  
    String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5 
    //hashcode: -1390239557 dir1: 11 dir: 11 ( In order to d507ef2e-aca9-4908-a8b9-c1d1c6a2f4d9_ Japanese 2 Level grammar corpus ( recommended ).doc For example, ) 
    System.out.println(" Before uploading :hashcode: "+ hashcode + " dir1: " +dir1 + " dir: " + dir2); 
    //File It can represent either a file or a directory  
    File file = new File(dir); 
    // If the directory does not exist  
    if(!file.exists()){ 
      // Create a directory  
      file.mkdirs(); 
    } 
    return dir; 
  } 
  public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    doGet(request, response); 
  } 
} 
// ---------------------------------------------------------- Simple version , The upload space and the file name of the upload are not handled  
// 
//import java.io.File; 
//import java.io.FileOutputStream; 
//import java.io.IOException; 
//import java.io.InputStream; 
//import java.util.List; 
//import javax.servlet.ServletException; 
//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; 
// 
//public class UploadHandleServlet extends HttpServlet { 
// 
//  public void doGet(HttpServletRequest request, HttpServletResponse response) 
//      throws ServletException, IOException { 
//        // Get the saved directory of uploaded files, and store the uploaded files in WEB-INF Under the directory, the external direct access is not allowed to ensure the security of uploaded files  
//        String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); 
//        File file = new File(savePath); 
//        // Determines if the save directory for the uploaded file exists  
//        if (!file.exists() && !file.isDirectory()) { 
//          System.out.println(savePath+" The directory does not exist and needs to be created "); 
//          // Create a directory  
//          file.mkdir(); 
//        } 
//        // Message prompt  
//        String message = ""; 
//        try{ 
//          // use Apache Steps to handle file upload:  
//          //1 , create, 1 a DiskFileItemFactory The factory  
//          DiskFileItemFactory factory = new DiskFileItemFactory(); 
//          //2 , create, 1 File upload parser  
//          ServletFileUpload upload = new ServletFileUpload(factory); 
//           // Solve the Chinese code of the upload file name  
//          upload.setHeaderEncoding("UTF-8");  
//          //3 Determine whether the submitted data is the data of the upload form  
//          if(!ServletFileUpload.isMultipartContent(request)){ 
//            // Get the data the traditional way  
//            return; 
//          } 
//          //4 , the use of ServletFileUpload The parser parses the uploaded data, and the parsed result returns 1 a List<FileItem> Each set, 1 a FileItem The corresponding 1 a Form The input to the form  
//          List<FileItem> list = upload.parseRequest(request); 
//          for(FileItem item : list){ 
//            // if fileitem Encapsulates the data for common input items  
//            if(item.isFormField()){ 
//              String name = item.getFieldName(); 
//              // Solve the Chinese scrambling problem of common input data  
//              String value = item.getString("UTF-8"); 
//              //value = new String(value.getBytes("iso8859-1"),"UTF-8"); 
//              System.out.println(name + "=" + value); 
//            }else{// if fileitem Encapsulates the upload file  
//              // Get the name of the uploaded file,  
//              String filename = item.getName(); 
//              System.out.println(filename); 
//              if(filename==null || filename.trim().equals("")){ 
//                continue; 
//              } 
//              // Note: Different browsers submit file names that are not 1 Similarly, some browsers submit file names with paths, such as:  c:\a\b\1.txt , while some are simply file names, such as: 1.txt 
//              // Process the path part of the filename of the uploaded file to get, leaving the filename part alone  
//              filename = filename.substring(filename.lastIndexOf("\\")+1); 
//              // To obtain item Input stream to the uploaded file  
//              InputStream in = item.getInputStream(); 
//              // create 1 A file output stream  
//              FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); 
//              // create 1 A buffer  
//              byte buffer[] = new byte[1024]; 
//              // An identifier that determines whether the data in the input stream has been read  
//              int len = 0; 
//              // The loop reads the input stream into the buffer, (len=in.read(buffer))>0 It means in There's data in there  
//              while((len=in.read(buffer))>0){ 
//                // use FileOutputStream The output stream writes the buffer's data to the specified directory (savePath + "\\" + filename) among  
//                out.write(buffer, 0, len); 
//              } 
//              // Close the input stream  
//              in.close(); 
//              // Close the output stream  
//              out.close(); 
//              // Deletes temporary files generated when processing file uploads  
//              item.delete(); 
//              message = " File upload successful! "; 
//            } 
//          } 
//        }catch (Exception e) { 
//          message= " File upload failed! "; 
//          e.printStackTrace(); 
//           
//        } 
//        request.setAttribute("message",message); 
//        request.getRequestDispatcher("/message.jsp").forward(request, response); 
//  } 
// 
//  public void doPost(HttpServletRequest request, HttpServletResponse response) 
//      throws ServletException, IOException { 
// 
//    doGet(request, response); 
//  } 
//}</span> 
< Upload file finished >

1.listfile.jsp


<span style="font-family:SimSun;font-size:14px;"><%@ 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 the file display page </title> 
  <meta charset="UTF-8"> 
  <style type="text/css"> 
    .filelistTab{ 
      width: 500px; 
      border: 2px solid gray; 
      border-collapse: collapse; 
    } 
    .filelistTd{ 
      height:25px; 
      border: 1px solid gray; 
    } 
  </style> 
</head> 
<body> 
 <%-- 
 <c:url var="path" value="download/downLoadServlet"> 
  <c:param name="filename" value="myOPQ"></c:param> 
 </c:url> 
 <a href="${path }" rel="external nofollow" rel="external nofollow" > The download file </a> 
 --%> 
 <!--  traverse Map A collection of  --> 
 <table class="filelistTab"> 
 <c:forEach items="${fileNameMap }" var="fileNames"> 
    <tr> 
      <td class="filelistTd"> 
        <c:url value="download/downLoadServlet" var="path"> 
          <c:param name="filename" value="${fileNames.key}"></c:param> 
        </c:url>${fileNames.value} 
      </td> 
      <td class="filelistTd"><a href="${path }" rel="external nofollow" rel="external nofollow" > download </a></td> 
    </tr> 
 </c:forEach> 
 </table> 
</body> 
</html></span> 

2.ListFileServlet.java


<span style="font-family:SimSun;font-size:14px;">package com.zeng.controller; 
import java.io.File; 
import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
/** 
* @ClassName: ListFileServlet 
* @Description:  list Web All downloaded files in the system  
*/  
public class ListFileServlet extends HttpServlet { 
  /* 
   * ListFileServlet In the listfile Method, listfile Method is used to list all files in the directory,  
   * listfile Method USES recursion internally, and in real development, we would definitely create it in the database 1 Table,  
   *  It will store the file name uploaded and the specific directory of the file. We can know the specific directory of the file through the query table.  
   *  There is no need to use recursion, this example is because there is no database to store the uploaded file name and the location of the file.  
   *  And the location where the uploaded files are stored USES the hash algorithm, so we need to use recursion, and during the recursion,  
   *  Store the obtained file name to be passed from outside to listfile Method inside Map In the set,  
   *  This ensures that all documents are stored in the same place 1 a Map Student: Assembly.  
   * */ 
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // Gets the directory of the uploaded files  
    String uploadFilePath = this.getServletContext().getRealPath("/WEB-INF/upload"); 
    // Store the file name to download  
    Map<String,String> fileNameMap = new HashMap<String,String>(); 
    // 
    File file = new File(uploadFilePath); 
    if(!file.exists()){ 
      // If the file path does not exist , The forwarded  
      request.setAttribute("message", " The path is an empty path "); 
      request.getRequestDispatcher("message.jsp").forward(request, response); 
    }else{ 
      // If the file path exists , Goes through all the files  
      // The recursive traversal filepath All files and directories under the directory, store the file name of the file to map In the collection  
      listfile(file,fileNameMap);//File Both can represent 1 Individual files can also be represented 1 A directory  
      // will Map Set sent to listfile.jsp Page display  
      request.setAttribute("fileNameMap", fileNameMap); 
      request.getRequestDispatcher("listfile.jsp").forward(request, response); 
    } 
  } 
  /** 
  * @Method: listfile 
  * @Description:  Recursively traverses all files in the specified directory  
  * @param file  Which stands for 1 A file, also represents 1 File directory  
  * @param map  Store file name Map A collection of  
  */  
  public void listfile(File file,Map<String,String> map){ 
    // if file Does not represent 1 A file, but 1 A directory  
    if(!file.isFile()){ 
      // Lists all the files and directories in this directory  
      File files[] = file.listFiles(); 
      // traverse files[] An array of  
      for(File f : files){ 
        // recursive  
        listfile(f,map); 
      } 
    }else{ 
      /** 
       *  Process file name, upload the file with uuid_ Filename to rename, filename to remove uuid_ Part of the  
        file.getName().indexOf("_") Retrieves the value of a string 1 time "_" Position of the character if the filename is similar to: 9349249849-88343-8344_ o _ every _ da .avi 
         then file.getName().substring(file.getName().indexOf("_")+1) After processing you can get a _ every _ da .avi Part of the  
       */ 
      String realName = file.getName().substring(file.getName().indexOf("_")+1); 
      //file.getName() You get the original name of the file, which is unique 1 So it can be used as key . realName Is a processed name that may be repeated  
      map.put(file.getName(), realName); 
    } 
  } 
  public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    doGet(request, response); 
  } 
}</span> 

< Show the completion of >

1.DownLoadServlet.Java


<span style="font-family:SimSun;font-size:14px;">package com.zeng.controller; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.net.URLEncoder; 
import javax.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 { 
    System.out.println(" Enter the "); 
    /* 
     * fileName The format of the : File name with: uuid+"_"+ The original name of the file   
     *  get fileName:d507ef2e-aca9-4908-a8b9-c1d1c6a2f4d9_ Japanese 2 Level grammar corpus ( recommended ).doc 
     * 
     * listfile.jsp Path is passed with  download/downLoadServlet submit  
     * 
     *  The path content is : 
     *   /FileUploadAndDownload/download/downLoadServlet 
     *     ?filename=d507ef2e-aca9-4908-a8b9-c1d1c6a2f4d9_ Japanese 2 Level grammar corpus ( recommended ).doc 
     * */ 
    String fileName = request.getParameter("filename"); 
    //      Pay attention to : The following is used 1 Sentence character transcoding , error : Unable to type file , 
    //dir1 and dir2 The Numbers are different , Causes the file to be recreated , There is no file in the file , Unable to find file error  
    //fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8"); 
    System.out.println("fileName: " + fileName); 
    // All uploaded files are saved in /WEB-INF/upload In a subdirectory under the directory  
    String fileSaveRootPath=this.getServletContext().getRealPath("/WEB-INF/upload"); 
    System.out.println("fileSaveRootPath: "+ fileSaveRootPath); 
    // Find the directory of the file by using the file name  
    String path = findFileSavePathByFileName(fileName,fileSaveRootPath); 
    System.out.println("path: "+ path); 
    // Server installation location \wtpwebapps\FileUploadAndDownload\WEB-INF\ upload\11\11 
    // Get the file you want to download , The file type is  : uuid + "_" +  The file name  
    File file = new File(path + "\\" + fileName); 
    System.out.println("file: "+ file.getAbsolutePath()); 
    // If the file does not exist  
    if(!file.exists()){ 
      request.setAttribute("message", " The resource you downloaded has been deleted!! "); 
      // Forward to the error page , Note the path problem here  
      request.getRequestDispatcher("../message.jsp").forward(request, response); 
      return; 
    } 
    // Handle filename , Get to remove uuid After filename  
    String realname = fileName.substring(fileName.indexOf("_")+1); 
    System.out.println("realname: "+ realname);       
    /* 
     *  File download  
     *  Set up the content-disposition The response header controls the browser to open the file as a download  
     *  When downloading A Chinese file, it is important to note that the Chinese file name should be used  
     * URLEncoder.encode() Method coding (URLEncoder.encode(fileName, " A character encoding ")) .  
     *  Otherwise, the file name will appear.  
     * */ 
    response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8")); 
    // Read the file to download and save it to the file input stream , The path here still has the uuid 
    FileInputStream in = new FileInputStream(path + "\\" + fileName); 
    // Create an output stream  
    OutputStream out = response.getOutputStream(); 
    // Create buffer  
    byte buffer[] = new byte[1024]; 
    int len = 0; 
    // A loop reads 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 achieve 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 by using the file name and storing the upload root directory  
  * @param filename  The file name to download  
  * @param saveRootPath  Upload to the root directory where the file is saved, i.e /WEB-INF/upload directory  
  * @return  The storage directory for the files to download  
  */  
  public String findFileSavePathByFileName(String filename,String saveRootPath){ 
    int hashcode = filename.hashCode(); 
    int dir1 = hashcode&0xf; //0--15 
    int dir2 = (hashcode&0xf0)>>4; //0-15 
    String dir = saveRootPath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5 
    //hashcode: -1390239557 dir1: 11 dir: 11 ( In order to d507ef2e-aca9-4908-a8b9-c1d1c6a2f4d9_ Japanese 2 Level grammar corpus ( recommended ).doc For example, ) 
    System.out.println("hashcode: "+ hashcode + " dir1: " +dir1 + " dir: " + dir2); 
    File file = new File(dir); 
    if(!file.exists()){ 
      // Create a directory  
      file.mkdirs(); 
    } 
    return dir; 
  } 
  public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    doGet(request, response); 
  } 
}</span> 

Related articles: