File upload and download for SpringMVC

    SpringMVC will convert and bind the information in the request message to the parameters of the request method in a certain way according to the different signatures of the request method. During the time when the request message arrives at the actual call processing method, SpringMVC will also complete a lot of other work, including request message conversion, data conversion, data formatting, and data validation.

One: SpringMVC realizes file upload

    In order to upload the file, the method of the form must be set to POST, and the enctype must be set to multipart/form-data. In this case, the browser will send the binary data of the file selected by the user to the server. SpringMVC provides direct support for file upload, which is implemented with plug-and-play MultipartResolver, so SpringMVC's file upload component also needs to rely on the Apache Commons FileUpload component.

<!-- File upload component -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

    Case: File upload of SpringMVC

        1. Add a Bean file to the SpringMVC.xml file

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--Upload file size limit in bytes (10M)-->
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
        <!--The encoding format of the request must be consistent with the pageEncoding attribute of jsp so that the content of the form can be read correctly. The default is IS0-8859-1 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

    2. Writing jsp pages are registerForm.jsp, userInfo.jsp, error.jsp   

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User registration</title>
</head>
<body>
    <h2>User registration</h2>
    <form action="register" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>Please upload an image:</td>
                <td><input type="file" name="image"/></td>
            </tr>
            <tr>
                <td><input type="submit" name="注册"/></td>
            </tr>
        </table>
    </form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h2>File Download</h2>
    <a href="download?filename=${requestScope.user.image.originalFilename}">
        ${requestScope.user.image.originalFilename}
    </a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    error page
</body>
</html>

    3. Controller class

@RequestMapping("/register")
    public String register(HttpServletRequest request, @ModelAttribute User user, Model model)throws Exception{
        if(!user.getImage().isEmpty()){
            /**Path to upload file*/
            String path = request.getSession().getServletContext().getRealPath("/images/");
            System.out.println(path);
            /**Upload file name*/
            String filename = user.getImage().getOriginalFilename();
            File filepath = new File(path,filename);
            /** Create if the path exists or not*/
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            /**Save the uploaded file with the target file*/
            user.getImage().transferTo(new File(path+File.separator+filename));
            /**Add user to model*/
            model.addAttribute("user",user);
            /**Jump*/
            return "userInfo";
        }else{
            return "error";
        }
    }

    
package com.jz.demo;
import org.springframework.web.multipart.MultipartFile;
public class User {
    private String username;
    private MultipartFile image;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public MultipartFile getImage() {
        return image;
    }

    public void setImage(MultipartFile image) {
        this.image = image;
    }
}

Two: file download

    SpringMVC provides a ResponseEntity type, which can be used to easily define the returned HttpHeaders.

    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model)throws Exception{
        // download file path
        String path = request.getSession().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 garbled Chinese names
        String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8");
        // Notify the browser to open the image with attachment (download method)
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream : binary stream data (most common for file downloads).
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 201 HttpStatus.CREATED
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325618271&siteId=291194637