In SpringMVC, file uploads are implemented through the MultipartResolver. So, if you want to implement file upload, just register the corresponding MultipartResolver in spring-mVC.xml.

There are two classes that implement MultipartResolver:

CommonsMultipartResolver StandardServletMultipartResolver the difference between the two:

The first requires Apache’s Commons-Fileupload and other JAR package support, but it can be used in older servlet versions. The second, which does not require third-party JAR package support, uses the upload functionality built into servlets, but only available in servlets 3 and older. The first step:

Use two packages / / CommonsMultipartResolver upload

“Commons fileupload: Commons fileupload: – 1.3.1”,

“Commons – IO: Commons – IO :2.4”

The dispatcher – servlet. XML configuration:

<context:component-scan base-package="edu.nf.ch08.controller"/> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <! -- There are two types of file upload, one is based on Servlet3.0 upload, the other is based on Commons -upload. If you use Servlet3.0 upload, you do not need to configure MultipartResolver. Spring will register a StandardServletMultipartResolver by default. Just enable <multipart-config> in web.xml. If you want to use the Commons - the upload, you need to configure a CommonsMultipartResolver, and the id at the specified bean multipartResolver -- > <! Commons --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <! <property name="maxUploadSize" value="104857600"/> <! <property name="defaultEncoding" value=" UTF-8 "/> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>Copy the code

Web.xml:

<! <servlet> <servlet-name> </servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:dispatcher-servlet.xml</param-value> </init-param>  </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>Copy the code

Java (upload, download) processing code: package edu.nf.ch08.controller;

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.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView;

import java.io.File; import java.io.IOException;

/ * *

  • @author wangl

  • @date 2018/11/2 */ @Controller public class UploadController {

    / * *

    • All Spring needs to do to upload a file is pass in a MultipartFile object,
    • This object can get information about file uploads.
    • A MultipartFile represents a single file upload, when multiple files need to be uploaded
    • Just declare it as the MultipartFile[] array.
    • @return */ @postmapping (“/upload”) public ModelAndView upload(MultipartFile file){// Get the current system user directory String home = System.getProperty(“user.home”); File uploadDir = new File(home + “/files”); // If the directory does not exist, create if(! uploadDir.exists()){ uploadDir.mkdir(); String fileName = file.getoriginalfilename (); / / build a complete File upload object File uploadFile = new File (uploadDir. GetAbsolutePath () + “/” + fileName); Try {// Upload file.transferTo(uploadFile); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } mv = new ModelAndView(“index”); mv.addObject(“fileName”, fileName); return mv; }

    / * *

    • File download
    • Read the server local file and encapsulate it as a ResponseEntity object
    • The client writes back an array of bytes
    • @param fileName Specifies the name of the file
    • @return */ @getmapping (“/download”) public ResponseEntity

      download(String fileName){// build a local file path based on the fileName String filePath = System.getProperty(“user.home”) + “/files/” + fileName; File File = new File(filePath); HttpHeaders headers = new HttpHeaders(); String headerFileName = new String(filename.getBytes (“UTF-8”), “ISO-8859-1″); / / set the response content approach to accessories, and specify the file headers. SetContentDispositionFormData (” attachment “, headerFileName); // Set the response header type to application/octet-stream, indicating a stream type headers. SetContentType (MediaType.APPLICATION_OCTET_STREAM); / / transform file into a byte array byte [] bytes = FileUtils. ReadFileToByteArray (file); ResponseEntity

      entity = new ResponseEntity<>(bytes, headers, ResponseEntity) HttpStatus.CREATED); // Return the whole ResponseEntity object to DispatcherServlet return entity; } catch (Exception e) { e.printStackTrace(); Throw new RuntimeException(” file download failed “); }}}
      []>
      []>

Upload file to webpage HTML:

File upload





JSP (download file) page forwarded after successful upload:

<%– Created by IntelliJ IDEA. User: wangl Date: 2018/11/2 Time: 09:56 To change this template use File | Settings | File Templates. –%> <%@ page contentType=”text/html; charset=UTF-8″ language=”java” %>

${fileName}

Project Structure: