Servlet file upload and download (detailed case)

Learning reference link

Servlet file upload and download

This article uses the famous file upload and download component implementation under Apache

  • org.apache.commons.fileupload
  • org.apache.commons-io-2.5

Download link: https://pan.baidu.com/s/1pJMHjR2natN7m1T9hy_z_g
Extraction code: mxmd

Demo address access

[project directory]

  • Upload directory: current project / out/artifacts/Tomcat virtual directory / File (run auto create)
  • Download Directory: click the page hyperlink to download (put the resource file into the web/img under the project file first)
  • DownLoadServlet.java: Download processing Servlet
  • UploadServlet.java: upload processing Servlet
  • DownLoadUtils.java: Browser coding tool class
  • index.jsp: file upload download form page
  • lib stores commons-fileupload.jar and commons-io.jar

To configure

Unrecognized problem of creating Web project and Servlet jar package

[step by step reference]

Add jar package to classpath


Tomcat virtual directory

File download

DownLoadServlet

package org.iqqcode.servlet.file;

import org.iqqcode.servlet.utils.DownLoadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author: Mr.Q
 * @Date: 2020-02-13 16:56
 * @Description:File download
 */
@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //1. Get request parameters, file name
        String fileName = request.getParameter("fileName");

        //2. Use byte input stream to load file into memory

        //2.1 find the file server path
         ServletContext servletContext = this.getServletContext();
         String realPath = servletContext.getRealPath("/img/" + fileName);

         //2.2 read files into memory with byte stream
        FileInputStream file = new FileInputStream(realPath);

        //3. Set response response header

        //3.1 set response header type: content type
        //Get file MIME type
        String fileType = servletContext.getMimeType(fileName);
        response.setHeader("content-type",fileType);

        //3.2 set the opening method of response header: content disposition

        //Solve the problem of Chinese file name

        //1. Get user agent request header
        String agent = request.getHeader("user-agent");
        //2. Using tool class method to encode file name
        fileName = DownLoadUtils.getFileName(agent, fileName);

        response.setHeader("content-disposition","attachment;fileName" + fileName);

        //4. Write out the data in memory to the output stream
        ServletOutputStream sos = response.getOutputStream();
        //Set cache
        byte[] buffer = new byte[1024 * 8];
        int len = 0;
        while ((len = file.read(buffer)) != -1) {
            sos.write(buffer, 0, len);
        }

        //Closed flow
        file.close();
        sos.close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doPost(request, response);
    }
}

Set the browser coding tool class, so that the resource files under img can be named in Chinese

DownLoadUtils

package org.iqqcode.servlet.utils;


import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Author: Mr.Q
 * @Date: 2020-02-13 18:35
 * @Description:Browser coding tool class
 */
public class DownLoadUtils {
    public static String getFileName(String agent,String filename) throws UnsupportedEncodingException {
        if(agent.contains("MSIE")) {
            //IE browser
            filename = URLEncoder.encode(filename,"utf-8");
            filename = filename.replace("+"," ");
        } else if (agent.contains("Firefox")) {
            //Firefox
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-82B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        } else {
            //Other browsers
            filename = URLEncoder.encode(filename,"utf-8");
        }
        return filename;
    }
}

File upload

UploadServlet

package org.iqqcode.servlet.file;

import java.io.*;
import java.util.List;
import java.util.UUID;
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 {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        try {
            //Create a factory
            DiskFileItemFactory factory = new DiskFileItemFactory();
            File file = new File("/File");
            if (!file.exists()) {
                file.mkdir();
            }

            //Set cache path for files
            factory.setRepository(file);

            //Create fileupload component
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            fileUpload.setHeaderEncoding("GBK");

            //Parse request
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            PrintWriter write = response.getWriter();
            //Ergodic set
            for (FileItem fileItem : fileItems) {
                //Judge whether it is a normal field
                if (fileItem.isFormField()) {
                    //Get field name and field value
                    String name=fileItem.getFieldName();
                    String value=fileItem.getString("GBK");
                    write.println("Uploads:" + value);
                } else {
                    //Upload file path
                    String filename = fileItem.getName();
                    write.println("Source:" + filename);
                    //Intercept file name
                    filename = filename.substring(filename.lastIndexOf("\\")+1);
                    write.println("Files uploaded successfully:" + filename);
                    //Unique file name
                    filename = UUID.randomUUID().toString() + "_" + filename;
                    //Create a file with the same name on the server
                    String webPath = "/File/";
                    String filepath = getServletContext().getRealPath(webPath+filename);
                    //create a file
                    File fileNew = new File(filepath);
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                    //Get upload stream
                    InputStream in = fileItem.getInputStream();
                    //Get write stream
                    OutputStream out = new FileOutputStream(fileNew);
                    //Set cache
                    byte[] buffer = new byte[1024 * 8];
                    int len ;
                    while((len = in.read(buffer)) > 0){
                        out.write(buffer, 0, len);
                    }
                    //Closed flow
                    in.close();
                    out.close();
                    //Delete temporary files
                    fileItem.delete();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
    }
}

File upload and download form page

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>UploadDownload</title>
  </head>
  <body>
  <h2>File upload</h2>
  <form action="/ServletFile/UploadServlet" method="post" enctype="multipart/form-data">
    <table width = "500px">
      <tr>
        <td>Uploads</td>
        <td><input type="text" name="name"></td>
      </tr>
      <tr>
        <td>Upload files</td>
        <td><input type="file" name="myfile"></td>
      </tr>
      <tr>
        <td colspan="2"> <input type="submit"value="upload"/></td>
      </tr>
    </table>
  </form>
  <br>
  <hr>
  <br>
  <h2>File download</h2>
  <table width = "300px">
    <tr>
      <td>File Preview</td>
      <td>
        <a href="/ServletFile/img/Yun Yun.jpg">picture</a>
        <a href="/ServletFile/img/11.avi">video</a>
      </td>
    </tr>
    <tr>
      <td>Upload and download</td>
      <td>
        <a href="/ServletFile/DownLoadServlet?fileName=Yun Yun.jpg">picture</a>
        <a href="/ServletFile/DownLoadServlet?fileName=11.avi">video</a>
      </td>
    </tr>
  </table>
  </body>
</html>

test

My project's access address: http://localhost:8080/ServletFile/


Upload succeeded:


Download and click hyperlink directly!

85 original articles published, 124 praised, 30000 visitors+
Private letter follow

Tags: Java Apache JSP Firefox

Posted on Fri, 14 Feb 2020 11:05:35 -0500 by ZachEdwards