Upload and download spring MVC files

File upload is one of the most common functions in project development. Spring MVC can well support file upload, but MultipartResolver is not installed in the spring MVC context by default, so it cannot handle file upload by default. If you want to use spring's file upload function, you need to configure MultipartResolver in the context.

Front end form requirements: in order to upload files, the method of the form must be set to POST and the enctype must be set to multipart / form data. Only in this case, the browser will send the file selected by the user to the server as binary data;

Give a detailed description of the enctype attribute in the form:

attributeexplain
application/x-www=form-urlencodedBy default, only the value attribute value in the form field is processed. Forms with this encoding method will process the value in the form field as URL encoding.
multipart/form-dataThis encoding method will process form data in the form of binary stream. This encoding method will also encapsulate the contents of the file specified in the file field into the request parameters, and will not encode characters.
text/plainIn addition to converting the space into a "+" sign, other characters are not encoded. This method is suitable for sending mail directly through the form.
    <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="file">
        <input type="submit" name="upload">
    </form>

Once the enctype is set to multipart / form data, the browser will process the form data in the form of binary stream, and the processing of file upload involves parsing the original HTTP response on the server side. In 2003, the Apache Software Foundation released the open source Commons FileUpload component, which soon became the best choice for Servlet/JSP programmers to upload files.

The Servlet 3.0 specification already provides methods to handle file uploads, but such uploads need to be done in the Servlet. Spring MVC provides a simpler encapsulation. Spring MVC provides direct support for file upload, which is implemented with the plug and play MultipartResolver. Spring MVC implements a MultipartResolver implementation class using Apache Commons FileUpload Technology:

CommonsMultipartResolver. Therefore, the file upload of spring MVC also depends on the component of Apache Commons FileUpload.

File upload

1. Import jar package

<!--File upload-->
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>
<!--servlet-api Import a later version of-->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
</dependency>

2. Configuration bean: multipartResolver

    <!--File upload configuration-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--The encoding format of the request must be and jsp of pageEncoding Property is consistent so that the contents of the form can be read correctly. The default is ISO-8859-1-->
        <property name="defaultEncoding" value="utf-8"></property>
        <!--Upload file size limit, in bytes(10485760=10M)-->
        <property name="maxUploadSize" value="10485760"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>

The id must be multipartResolver, or an error will be reported.

CommonsMultipartFile

CommonsMultipartFile inherits the common methods of MultipartFile:

code implementation

Front page

index.jsp

<%@ page contentType="text/html; charset=utf-8" language="java"%>
<html>
<head>
    <title>Hello!</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="file">
        <input type="submit" name="upload">
    </form>
</body>
</html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
	${msg}
</body>
</html>

Controller

/**
 * @author acoffee
 * @create 2021-11-23 17:29
 */
@Controller
public class FileController {

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile, Model model) throws IOException {
        String uploadFile = multipartFile.getOriginalFilename();

        //If the file name is empty, go back to the home page directly
        if ("".equals(uploadFile)) {
            return "redirect:/index.jsp";
        }

        //Upload path save settings
        String realPath = request.getServletContext().getRealPath("/images/");
        //Uploaded file name
        String filename = multipartFile.getOriginalFilename();

        //If the path does not exist, create one
        File realFile = new File(realPath);
        if (!realFile.exists()) {
            realFile.mkdir();
        }

        //Copy the file to the location we specified
        multipartFile.transferTo(new File(realPath + File.separator + filename));

        model.addAttribute("msg", "The path successfully inserted is:" + new File(realPath + "/" + filename));

        return "success";
    }
}

Test results:


File download

Front page

<h2>File download</h2>
<form action="download" enctype="multipart/form-data" method="post">
    <table>
        <tr>
            <td>File name:</td>
            <td><input type="text" name="filename">
            </td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" name="Submit"></td>
        </tr>
    </table>
</form>

Mode 1:

    //Mode 1
    @RequestMapping("/download")
    public String downloads(@RequestParam("filename")String filename,HttpServletResponse response,HttpServletRequest request) throws Exception {
        //Address to download pictures
        String realPath = request.getServletContext().getRealPath("/images/");

        System.out.println(filename);
        //1. Set the response header
        response.reset();//Page not cached
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");//Binary transmission data

        //Set response header

        response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(filename, "UTF-8"));

        File file = new File(realPath, filename);

        //Reading files: input streams
        FileInputStream inputStream = new FileInputStream(file);
        //Write files: output streams
        OutputStream outputStream = response.getOutputStream();

        byte[] bytes = new byte[1024];
        int index = 0;
        while ((index=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,index);
            outputStream.flush();
        }

        outputStream.close();
        inputStream.close();

        return null;
    }

Mode 2:

	/*
	Download through the file name, and refer to the upload path for the path
	For later development, the path refers to the url address (such as using cloud services), or
	Reference the path location stored in the database
	*/
    @RequestMapping("/download")
    public ResponseEntity<byte[]> downLoad(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model) throws UnsupportedEncodingException {
        //Get download file path
        String path = request.getServletContext().getRealPath("/images/");
        File file = new File(path + "/" + filename);
        HttpHeaders httpHeaders = new HttpHeaders();
        
		//Download the displayed file name to solve the problem of Chinese name confusion
        String downloadFilename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
        
		//Notify the browser to open the picture with attachment
        httpHeaders.setContentDispositionFormData("attachment", downloadFilename);
        
		//Application / octet stream: binary stream data (the most common file download)
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try {
            return new ResponseEntity(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
        } catch (IOException e) {
            HttpHeaders httpHeader1 = new HttpHeaders();
            httpHeader1.setContentType(MediaType.APPLICATION_JSON);
            return new ResponseEntity("File name error!", httpHeader1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

Keywords: Spring MVC Java framework

Added by cleary1981 on Wed, 24 Nov 2021 07:11:07 +0200