SoFunction
Updated on 2025-03-09

Upload and download files in JavaWeb

File upload

1. There must be a form tag, method=post request

The value of the encType property of the tag must be a multipart/form-data value

3. Use input type=file in the from tag to add uploaded file

4. Write server code to receive uploaded data

Content-Type: Indicates the submitted data type

enctype="multipart/form-data": represents the submitted data, spliced ​​in the form of multiple segments (one data segment per form), and then sent to the server in the form of a binary stream.

boundary: The delimiter representing each piece of data

---WebKitFormBoundaryOZ1BoZwqflbGWUBH is generated randomly by the browser every time, and it is the delimiter of each piece of data.

package .file_upload;
 
import .*;
import .*;
 
import ;
 
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 
    }
 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ("File Upload");
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="/xml/ns/jakartaee"
         xmlns:xsi="http:///2001/XMLSchema-instance"
         xsi:schemaLocation="/xml/ns/jakartaee /xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>.file_upload.UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/uploadServlet</url-pattern>
    </servlet-mapping>
</web-app>
&lt;%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/3/15
  Time: 23:08
  To change this template use File | Settings | File Templates.
--%&gt;
&lt;%@ page contentType="text/html;charset=UTF-8" language="java" %&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action="http://localhost:8080/file_Upload/uploadServlet" method="post" enctype="multipart/form-data"&gt;
    username:&lt;input type="text" name="username"/&gt;

    avatar:&lt;input type="file" name="photo"/&gt;

    &lt;input type="submit" value="Upload"&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

Common APIs

Import commons-fileupload-1.3. and commons-io-2. package into the project lib directory

Commonly used categories:

  • ServletFileUpload class: used to parse uploaded data
  • FileItem class: represents each form item
  • boolean (HttpServletRequest request): determines whether the currently uploaded data format is a multi-section format
  • public List<FileItem> parseRequest(HttpServletRequest request): parse uploaded data
  • boolean isFormField(): determines whether the current form item is a normal form item or the uploaded file type. True represents the form item, and false represents the uploaded file type.
  • String getFieldName(): Get the name attribute value of the form item
  • String getString(): Get the value of the current form item
  • String getName(): Get the uploaded file name
  • void write(File var1) throws Exception: Write the uploaded file to the hard disk position pointed to by the parameter file

File upload test

package ;
 
import ;
import ;
import ;
import ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ("UTF-8");
        //First determine whether the uploaded data is multi-section data (only multi-section data is uploaded by the file)        if ((req)) {
            //Create FileItemFactory factory implementation class            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //Create a tool class for parsing uploaded data            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            //Analyze the uploaded data to get each form item Item            try {
                List&lt;FileItem&gt; list = (req);
                //Cycle to determine whether each form item is a normal type or upload file                for (FileItem fileItem : list) {
                    if (()) {
                        //Normal form items                        ("The name attribute value of the form item:" + ());
                        // Parameter UTF-8 solves Chinese garbled code                        ("Value value of form item:" + ("UTF-8"));
                    } else {
                        //Upload file                        ("The name attribute value of the form item:" + ());
                        ("Upload file name:" + ());
                        (new File("G:\\test" + ()));
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="/xml/ns/jakartaee"
         xmlns:xsi="http:///2001/XMLSchema-instance"
         xsi:schemaLocation="/xml/ns/jakartaee /xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">
    <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class></servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/uploadServlet</url-pattern>
    </servlet-mapping>
</web-app>
&lt;%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/3/15
  Time: 23:08
  To change this template use File | Settings | File Templates.
--%&gt;
&lt;%@ page contentType="text/html;charset=UTF-8" language="java" %&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action="http://192.168.42.31:8080/Upload_Web/uploadServlet" method="post" enctype="multipart/form-data"&gt;
    username:&lt;input type="text" name="username"/&gt;&lt;br&gt;
    avatar:&lt;input type="file" name="photo"/&gt;&lt;br&gt;
    &lt;input type="submit" value="Upload"&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

Download file

The client sends a request to tell the server what file it needs to download. The server used to download the file name, read the file content to download, and pass the downloaded file content back to the client. Before returning it, it tells the client the data type returned through the response header, and also tells the client the data received for downloading and using the response header.

Common API description:

  • (): Get the response output stream
  • (): Used to read the content to be downloaded (the return object is the input stream)
  • (): Get the file type to download
  • (): Before returning the data type is told to the client through the response header

("Content-Disposition", "attachment;fileName=" + ("Hello.png","UTF-8"));The response header tells the browser that this file is the file to be downloaded. attachment means attachment, that is, the downloaded file, fileName=the following indicates the downloaded file name

package .download_web;
 
import .*;
import .*;
import ;
 
import ;
import ;
import ;
import ;
 
public class Download extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Get the file name to download        String downloadFileName = "";
        //2. Read the file content to be downloaded (read through the ServletContext object)        ServletContext servletContext = getServletContext();
        //Get the file type to download        String mimeType = ("/file/" + downloadFileName);
        ("Downloaded file type:" + mimeType);
        //Before the return return, tell the client the data type returned through the response header        (mimeType);
        // Also tell the client whether the data received is used for download (or use response headers)        //Content-Disposition response header indicates how to process the received data        //attachment means the file name specified to download        //url encoding is to convert Chinese characters into %xx%xx format        ("Content-Disposition", "attachment;fileName=" + ("Hello.png","UTF-8"));
        InputStream resourceAsStream = ("/file/" + downloadFileName);
        //Get the response output stream        OutputStream outputStream = ();
        //Pause the file content to be downloaded back to the client        //Read all the data in the input stream and assign it to the output stream and output it to the client        (resourceAsStream, outputStream);
    }
 
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="/xml/ns/jakartaee"
         xmlns:xsi="http:///2001/XMLSchema-instance"
         xsi:schemaLocation="/xml/ns/jakartaee /xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    <servlet>
        <servlet-name>Download</servlet-name>
        <servlet-class>.download_web.Download</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Download</servlet-name>
        <url-pattern>/download</url-pattern>
    </servlet-mapping>
</web-app>

This is the article about uploading and downloading files in JavaWeb. For more related JavaWeb file upload and download content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!