Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Spring MVC realizes the upload and download of files

Shulou Source: shulou.com Published: 2022-06-03 06:13:58 10月01日 Update

In SpringMVC, the upload of files is achieved through MultipartResolver. So, if you want to upload files, just register the corresponding MultipartResolver in spring-mvc.xml.

There are two implementation classes for MultipartResolver:

CommonsMultipartResolver

StandardServletMultipartResolver

The difference between the two:

The first requires jar package support such as Apache's commons-fileupload, but it can be used in older versions of servlet.

The second one, which does not require third-party jar package support, uses servlet's built-in upload function, but can only be used in versions above Servlet 3.

The first step to use:

/ two packages used for CommonsMultipartResolver upload /

"commons-fileupload:commons-fileupload:1.3.1"

"commons-io:commons-io:2.4"

If it is a maven project, import it directly:

Commons-fileupload

Commons-fileupload

1.3.1

Dispatcher-servlet.xml configuration:

Web.xml:

Dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:dispatcher-servlet.xml dispatcher /

Backend java (upload and 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 Universe 11 Universe /

@ Controllerbr/ > * /

@ Controller

/ * *

To upload a file, you only need to pass in a MultipartFile object by Spring, which can obtain the information about the file upload. A MultipartFile means that a single file is uploaded, and when you need to upload multiple files, you only need to declare it as an MultipartFile [] array. @ return*/

@ PostMapping ("/ upload") br/ > * /

@ PostMapping ("/ upload")

/ / get the current system user directory

String home = System.getProperty ("user.home")

/ / specify the uploaded folder directory

File uploadDir = new File (home + "/ files")

/ / if the directory does not exist, create

If (! uploadDir.exists ()) {

UploadDir.mkdir ()

}

/ / get the name of the uploaded file

String fileName = file.getOriginalFilename ()

/ / build a complete file upload object

File uploadFile = new File (uploadDir.getAbsolutePath () + "/" + fileName)

Try {

/ / upload via transferTo method

File.transferTo (uploadFile)

} catch (IOException e) {

E.printStackTrace ()

Throw new RuntimeException (e.getMessage ())

}

/ / Save the file name into Model and forward it to the index page

ModelAndView mv = new ModelAndView ("index")

Mv.addObject ("fileName", fileName)

Return mv

}

/ * *

The file download reads the server local file and encapsulates it as a ResponseEntity object response client, writing back an array of bytes @ param fileName file name @ return*/

@ GetMapping ("/ download") br/ > * /

@ GetMapping ("/ download")

/ / build a local file path based on the file name

String filePath = System.getProperty ("user.home") + "/ files/" + fileName

/ / build File objects based on the file path

File file = new File (filePath)

/ / create a response header object and set the response information

HttpHeaders headers = new HttpHeaders ()

Try {

/ / A pair of file names are re-encoded to prevent Chinese garbled in the response header

String headerFileName = new String (fileName.getBytes ("UTF-8"), "ISO-8859-1")

/ / set the response content to be handled as an attachment and specify a file name

Headers.setContentDispositionFormData ("attachment", headerFileName)

/ / set the response header type to application/octet-stream, which means it is a stream type

Headers.setContentType (MediaType.APPLICATION_OCTET_STREAM)

/ / convert the file to a byte array

Byte [] bytes = FileUtils.readFileToByteArray (file)

/ / create ResponseEntity object (encapsulate file byte array, response header, response status code)

ResponseEntity entity = new ResponseEntity (bytes, headers, HttpStatus.CREATED)

/ / finally, the entire ResponseEntity object is returned to DispatcherServlet

Return entity

} catch (Exception e) {

E.printStackTrace ()

Throw new RuntimeException ("File download failed")

}

}

}

The web page where the file is uploaded is html:

Title

File upload

File:

Jsp (download file) page forwarded after a successful upload:

Title

${fileName}

Project structure:

Tags: File object file name array two byte method directory configuration information file download version type path page project processing encapsulation support success Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Shulou Information Docker Redmi Huawei