Spring MVC file upload and download function

Keywords: Java Session Attribute JSP

File upload

In order to upload the file successfully, you need to set the method attribute of the form to POST and the enctype to multipart / form data. Once it is set to multipart / form data, the browser will process the form data in binary. spring cannot process the file upload by default. You need to configure the MulipartResolver in the springmvc-config.xml configuration file.  

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- Maximum upload file size, in bytes (10 MB) -->
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
        <!-- Encoding format of the request, must be in combination with jSP Of pageEncoding The properties are consistent so that the contents of the form can be read correctly. The default value is ISO-8859-1 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

After MultipartResolver is configured, the file upload page is realized:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File upload</title>
<% String path = request.getContextPath(); %>
</head>
<body>
    <h2>File upload</h2>
    <form action="<%=path%>/upload" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>File description:</td>
                <td><input type="text" name="description"></td>
            </tr>
            <tr>
                <td>Please select a file:</td>
                <td><input type="file" name="file"></td>
            </tr>
            <tr>
                <td><input type="submit" value="upload"></td>
            </tr>
        </table>
    </form>
</body>
</html>

Create a FileUploadController to upload files. The main code is as follows:

// Upload files will be automatically bound to MultipartFile in
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest request, @RequestParam("description") String description,
            @RequestParam("file") MultipartFile file) throws Exception {
        System.out.println(description);
        // If the file is not empty, write the upload path
        if (!file.isEmpty()) {
            // Upload file path
            String path = request.getServletContext().getRealPath("/images/");
            // Upload file name
            String filename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            String name = uuid + filename.substring(filename.lastIndexOf("."));
            File filepath = new File(path, name);
            // Determine whether the path exists. If not, create a
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            // Save the uploaded file to a target file
            file.transferTo(new File(path + File.separator + name));
            // Copy files to development project path
            File source = new File(path + File.separator + name);
            File files = new File("D:\\workspace\\FileUpload\\WebContent\\image" + File.separator + name);
            Files.copy(source.toPath(), files.toPath());
            HttpSession session = request.getSession();
            session.setAttribute("path", "/image" + File.separator + name);
            session.setAttribute("name", name);
            return "success";
        } else {
            return "error";
        }

File download

The above implements the file upload function. Next, we implement the file download function. The file download is relatively simple. You only need to give a link on the page. You can download by equating the href attribute of the link to the file name of the file to be downloaded. springmvc provides a ResponseEntity type, which can be used to easily define the returned H Ttpheaders and HttpStatus.

Download page (success.jsp):

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>File download</title>
<%
    String name = (String) request.getSession().getAttribute("name");%>
</head>
<body>
    <p>Upload success</p>
    <h3>File download</h3>
    <a href="download?filename=<%=name%>"> <%=name%>
    </a>
</body>
</html>

After the processing method accepts the filename passed by the page, it uses the FileUtils of Apache Commons FileUpload component to read the upload file of the project, and constructs it as a ResponseEntity object to return to the client for download.

@RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,
            Model model) throws Exception {
        // Download file path
        String path = request.getServletContext().getRealPath("/images/");
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        // Download the displayed file name to solve the problem of Chinese name scrambling
        String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        // Notify browser to attachment(Download mode) open picture
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream :  Binary stream data (the most common file download).
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

The above is the file upload and download, if there is an exception, please leave a message!

Posted by James25 on Thu, 02 Jan 2020 01:30:31 -0800