File upload and download

File upload and download

File upload and download are very common functions. Many systems or software often use file upload and download. For example: QQ avatar, upload is used.
The mailbox also has the function of uploading and downloading attachments.
Upload of approved attachment materials in OA system.

I Introduction to file upload (* * * * key points)

1. HTTP protocol content sent during file upload
(1). To have a form tag, method=post request
(2). The value of the encType property of the form tag must be a multipart / form data value
(3). Use input type=file in the form tag to add the uploaded file
(4). Write server code (Servlet program) to receive and process uploaded data

Enctype = multipart / form data represents the submitted data, which is spliced in the form of multiple segments (one data segment for each form item), and then sent to the server in the form of binary stream

2.commons-fileupload.jar common API introduction
commons-fileupload.jar needs to rely on Commons io Jar package, so we need to introduce both packages.

The first step is to import two jar packages:
commons-fileupload-1.2.1.jar
commons-io-1.4.jar

commons-fileupload.jar and common io In the jar package, what are the commonly used classes?
ServletFileUpload class; Used to parse uploaded data.

boolean ServletFileUpload.isMultipartContent(HttpServletRequest request); Judge whether the currently uploaded data format is multi segment format.

Public list < fileitem > parserequest (HttpServletRequest request) parses the uploaded data.

boolean FileItem.isFormField() determines whether the current form item is an ordinary form item or an uploaded file type.
true indicates a common type of form item
false indicates the type of file uploaded

String FileItem.getFieldName()
Gets the name property value of the form item

String FileItem.getString()
Gets the value of the current form item

String FileItem.getName();
Get the uploaded file name

void FileItem.write(file);
Write the uploaded file to the location of the hard disk pointed to by the parameter file

3. Use of fileUpload class library
Use fileupload to parse the uploaded data
Code implementation:
upload.jsp

<%--
  Created by IntelliJ IDEA.
  User: thorns
  Date: 2021/12/31
  Time: 15:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:8080/EL_JSTL_war_exploded/upLoadServlet" method="post" enctype="multipart/form-data">
        user name:<input type="text" name="username" /><br>
        head portrait:<input type="file" name="photo" ><br>
        <input type="submit" value="upload">
    </form>
</body>
</html>

Import jar package

UpLoadServlet.java

package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class UpLoadServlet extends HttpServlet {
    /*Used to process uploaded data*/
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. First judge whether the uploaded data is multi segment data (only multi segment data is uploaded by file)
        if(ServletFileUpload.isMultipartContent(req)){
            //Create a FileItemFactory factory implementation class
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //Create a tool class ServletFileUpLoad class for parsing uploaded data
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //Parse the uploaded data to get each form item FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //Cycle to determine whether each form item is a common type or an uploaded file
                for(FileItem fileItem : list){
                    if(fileItem.isFormField()){
                        //Normal form item
                        System.out.println("Of form items name Attribute value:" + fileItem.getFieldName());
                        //Parameter UTF-8 to solve the problem of garbled code
                        System.out.println("Of form items name Attribute value:" + fileItem.getString("UTF-8"));
                    }else{
                        //Uploaded files
                        System.out.println("Of form items name Attribute value:" + fileItem.getFieldName());
                        System.out.println("Uploaded file name:" + fileItem.getName());

                        fileItem.write(new File("D:\\" + fileItem.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

web.xml

<servlet>
        <servlet-name>UpLoadServlet</servlet-name>
        <servlet-class>servlet.UpLoadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UpLoadServlet</servlet-name>
        <url-pattern>/upLoadServlet</url-pattern>
    </servlet-mapping>

Effect achieved:
1. The file is uploaded successfully. The uploaded file can be seen under the corresponding disk

2. Console output

II File download

Keywords: Java server jar

Added by ojeffery on Sun, 02 Jan 2022 13:52:04 +0200