Spring MVC Getting Started Guide (11): File Upload and Download

Use object to receive uploaded files

In the previous chapter, we demonstrated Spring MVC uploading files through a case . Next, we demonstrated using objects to receive uploaded files. 
In the development of actual projects, uploaded files are often saved as properties of objects. The processing of SpringMVC is also very simple.


Below we create the registerForm.jsp file in the views folder to demonstrate receiving file uploads:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>Insert title here</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>
<body>
    <h2>User registration</h2>
    <form action="file/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 avatar:</td>
                <td><input type="file" name="image"></td>
            </tr>
            <tr>
                <td><input type="submit" value="注册"></td>
            </tr>
        </table>
    </form>
</body>
</html>

Next, we create a package named "com.ray.entity", and then create a User class, which must implement the serialization interface, as shown in the following case code:

package com.ray.entity;

import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;

/**
 * @author Ray
 * @date 2018/4/22 0022
 * Implement serialization interface
 */
public class User implements Serializable {

    private String username;
    private MultipartFile image;

    public User() {
    }

    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;
    }
}

The FileController class we created earlier continues to write the upload and download functions for receiving files.

The following is the form function code responsible for receiving files----uploading files ( 2 ):

Description: Upload file path

    1.String path = servletContext.getRealPath("/upload") + "/"; //Project path/upload folder

    2.String path = "F:\\test\\"; //local path/test folder

/**
 * @author Ray
 * @date 2018/4/21 0021
 */
@Controller
@RequestMapping("/file")
public class FileController {

    /**
     * Upload file (1)
     * @return
     */
    @RequestMapping("/toFile")
    public String toFileUpload(){
        return "fileUpload";
    }

    /**
     * Upload file (2)
     * @return
     */
    @RequestMapping("/toFile2")
    public String toFileUpload2(){
        return "registerForm";
    }

    /**
     * Upload file (1)
     * Normal upload
     */
    @RequestMapping("/onefile")
    public String oneFileUpload(@RequestParam("file")CommonsMultipartFile file,
                                HttpServletRequest request, Model model){
        // get the original file name
        String fileName = file.getOriginalFilename();
        System.out.println("Original file name:" + fileName);

        //new file name
        String newFileName = UUID.randomUUID() + fileName;

        // get the project path
//        ServletContext servletContext = request.getSession().getServletContext();

        // upload location
// String path = servletContext.getRealPath("/upload") + "/"; //Project path/upload folder
        String path = "F:\\test\\"; //local path/test


        File f = new File(path);
        if(!f.exists()){
            f.mkdirs();
        }
        if(!file.isEmpty()){
            try{
                FileOutputStream fileOutputStream = new FileOutputStream(path + newFileName);
                InputStream inputStream = file.getInputStream();
                int b = 0;
                while ((b = inputStream.read()) != -1){
                    fileOutputStream.write(b);
                }
                fileOutputStream.close();
                inputStream.close();
            }catch (Exception e){
                e.printStackTrace ();
            }
        }

        // console output
        System.out.println("Upload image to: " + path + newFileName);
        //Save the file address for JSP page echo
        model.addAttribute("fileUrl",newFileName);
        return "fileUpload";
    }

    /**
     * Upload file (2)
     * user target audience
     */
    @RequestMapping(value = "/register")
    public String register(HttpServletRequest request, @ModelAttribute User user, Model model) throws IOException {
        System.out.println(user.getUsername());
        //If the file is not empty, write the upload path
        if(!user.getImage().isEmpty()){
            // upload file path
//            String path = request.getSession().getServletContext().getRealPath("/upload/");
            String path = "F:\\test\\"; //local path/test
            // upload file name
            String filename = user.getImage().getOriginalFilename();
            File filepath = new File(path, filename);
            / / Determine whether the path exists, if it does not exist, create it
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            //Save the uploaded file to a target file
            user.getImage().transferTo(new File(path + File.separator + filename));
            //Add user to model
            model.addAttribute("user",user);
            return "userInfo";
        }else {
            return "error";
        }
    }
}

Create the userInfo.jsp file in the views folder. This page is mainly the download page of the file. The following jsp code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>Insert title here</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>
<body>
    <h3>File Download</h3>
    <a href="file/download?filename=${requestScope.user.image.originalFilename}">${requestScope.user.image.originalFilename}</a>
</body>
</html>

Test the application by entering the following URL in your browser: 

http://localhost:8080/SpringMVC/file/toFile2

Enter your username and upload the file you just uploaded: 


Click the "Register" button to upload the file and you will be redirected to the download page. As shown below: 




document dowload

Above, we demonstrated the use of objects to receive uploaded files through the case. Next, we demonstrated Spring MVC's download files. 
The file download is relatively simple. A hyperlink is directly given on the page. The attribute of the link href is equal to the file name of the file to be downloaded, and the file download can be realized. However, if the file name of the file is Chinese, the download will fail on some early browsers; if the latest Firefox, Chrome, Opera, and Safari are used, the file with the Chinese file name can be downloaded normally. 
SpringMVC provides a ResponseEntity type, which can be used to easily define the returned HttpHeaders and HttpStatus. The following code demonstrates the download functionality of a file:

package com.ray.controllers;

import com.ray.entity.User;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io. *;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Ray
 * @date 2018/4/21 0021
 */
@Controller
@RequestMapping("/file")
public class FileController {

    /**
     * Upload file (1)
     * @return
     */
    @RequestMapping("/toFile")
    public String toFileUpload(){
        return "fileUpload";
    }

    /**
     * Upload file (2)
     * @return
     */
    @RequestMapping("/toFile2")
    public String toFileUpload2(){
        return "registerForm";
    }

    /**
     * Upload file (1)
     * Normal upload
     */
    @RequestMapping("/onefile")
    public String oneFileUpload(@RequestParam("file")CommonsMultipartFile file,
                                HttpServletRequest request, Model model){
        // get the original file name
        String fileName = file.getOriginalFilename();
        System.out.println("Original file name:" + fileName);

        //new file name
        String newFileName = UUID.randomUUID() + fileName;

        // get the project path
//        ServletContext servletContext = request.getSession().getServletContext();

        // upload location
// String path = servletContext.getRealPath("/upload") + "/"; //Project path/upload folder
        String path = "F:\\test\\"; //local path/test


        File f = new File(path);
        if(!f.exists()){
            f.mkdirs();
        }
        if(!file.isEmpty()){
            try{
                FileOutputStream fileOutputStream = new FileOutputStream(path + newFileName);
                InputStream inputStream = file.getInputStream();
                int b = 0;
                while ((b = inputStream.read()) != -1){
                    fileOutputStream.write(b);
                }
                fileOutputStream.close();
                inputStream.close();
            }catch (Exception e){
                e.printStackTrace ();
            }
        }

        // console output
        System.out.println("Upload image to: " + path + newFileName);
        //Save the file address for JSP page echo
        model.addAttribute("fileUrl",newFileName);
        return "fileUpload";
    }

    /**
     * Upload file (2)
     * user target audience
     */
    @RequestMapping(value = "/register")
    public String register(HttpServletRequest request, @ModelAttribute User user, Model model) throws IOException {
        System.out.println(user.getUsername());
        //If the file is not empty, write the upload path
        if(!user.getImage().isEmpty()){
            // upload file path
//            String path = request.getSession().getServletContext().getRealPath("/upload/");
            String path = "F:\\test\\"; //local path/test
            // upload file name
            String filename = user.getImage().getOriginalFilename();
            File filepath = new File(path, filename);
            / / Determine whether the path exists, if it does not exist, create it
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            //Save the uploaded file to a target file
            user.getImage().transferTo(new File(path + File.separator + filename));
            //Add user to model
            model.addAttribute("user",user);
            return "userInfo";
        }else {
            return "error";
        }
    }


    /**
     * document dowload
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model) throws IOException {
        // file path
//        String path = request.getSession().getServletContext().getRealPath("/upload/");
        String path = "F:\\test\\"; //local path/test
        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 downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        //Notify the browser to open the image with attachment (download method)
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //application_octet_stream : binary stream data (most common file download)
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }
}
After receiving the filename filename passed by the page, the download processing method uses the FileUtils of the Apache Commons FileUpload component to read the uploaded file of the project, and constructs it into a ResponseEntity object and returns it to the client for download. 
Using the ResponseEntity object, you can easily define the returned HttpHeaders and HttpStatus. The MediaType in the above code represents the Internet Media Type, that is, the Internet media type, also known as the MIME type. In the Http protocol message header, use Content-Type to represent the media type information in the specific request. The HttpStatus type represents the status in the Http protocol. For the MediaType and HttpStatus classes, please refer to the Spring MVC API documentation. 

Clicking on the hyperlink of the download page shows that the file is being downloaded, as shown in the image below: 



Easter eggs


Guess you like

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