Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to upload and download SpringMVC based on annotations

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to upload and download SpringMVC based on annotations, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this SpringMVC based on annotations. Let's take a look.

File download 1-1, servlet native download / * * servlet api-based file download * / @ RequestMapping ("/ download") public String download (HttpServletRequest request,HttpServletResponse response) throws IOException {/ / get the download file under the current project path (the real development Chinese file name must be read from the data) String realPath = request.getServletContext (). GetRealPath ("/ file/20181129204254948.png") / / encapsulated into a File object File tmpFile=new File (realPath) according to the file path; / / you can obtain the file name String fileName = tmpFile.getName () directly from the File object; / / set the response header content-disposition: set the opening mode of the file download, and open it on the web page by default. / / set attachment. Filename= is to download the file / / "UTF-8" setting will not garbled response.setHeader if the file name is in Chinese ("content-disposition", "attachment;filename=" + URLEncoder.encode (fileName, "UTF-8")); / / encapsulated into a file input stream InputStream in = new FileInputStream (realPath) according to the file path; int len = 0 / / buffer byte [] buffer = new byte [1024] that declares a byte of 1KB; / / gets the output stream OutputStream out = response.getOutputStream (); / / reads the file in a loop, reading 1KB each time to avoid memory overflow while ((len = in.read (buffer)) > 0) {/ / write out.write (buffer,0,len) to the client / / output the buffer data to the client browser} in.close (); return null;}

In the above code, we set the response header.

Response.setHeader ("content-disposition", "attachment;filename=" + URLEncoder.encode (fileName, "UTF-8"))

Content-disposition can be downloaded from the front end in the form of a file, otherwise it will be opened directly in the browser.

1-2. Use ResponseEntity to download

The content of the response data, the response header and the response status code can be customized at the same time

1-2-1. Use ResponseEntity to customize the response content.

Generally, in scenarios where the front and rear ends are separated, the front end requests the interface of the back end, and the back end generally returns three values, namely: request status, request data, and request information. Using ResponseEntity can help us customize such content.

From the figure above, we can see that the relevant data can be returned through ResponseEntity, and the response header and status code can also be set.

Also note that you can see that the return type of the method is Response

< String>

Then when we return ResponseEntity, the first parameter must be of type String. This is the value that returns the generics.

2-2-2. Download files using ResponseEntity

/ * * servlet api-based file download * / @ RequestMapping ("/ download02") public ResponseEntity download02 (HttpServletRequest request) throws IOException {/ / get the download file under the current project path (the real development Chinese file name must be read from the data) String realPath = request.getServletContext (). GetRealPath ("/ file/20181129204254948.png"); / / encapsulated into a File object File tmpFile=new File (realPath) according to the file path / / you can get the file name String fileName = tmpFile.getName (); HttpHeaders headers=new HttpHeaders (); headers.set ("content-disposition", "attachment;filename=" + URLEncoder.encode (fileName, "UTF-8")) directly from the File object; / / encapsulate the file input stream InputStream in = new FileInputStream (realPath) according to the file path; return new ResponseEntity (new byte [in.available ()], headers,HttpStatus.OK);}

You can see that data can also be downloaded using ResponseEntity, but the buffer cannot be set and can only be read all at once.

1-2-3, servlet download and ResponseEntity download difference

The difference between the two, using native servlet download, we can set the buffer, but not with ResponseEntity, can only read all the data of the file as a byte array at one time. To avoid memory overflow, it is recommended to download it native to servlet.

II. File upload

Spring MVC provides direct support for file uploads through plug-and-play MultipartResolver. Spring implements a MultipartResolver implementation class: CommonsMultipartResovler using Jakarta Commons FileUpload technology.

MultipartResovler is not installed by default in the context of Spring MVC, so file upload cannot be handled by default. If you want to use Spring's file upload feature, you need to configure MultipartResolver in the context now.

2-1. Add commons-fileupload dependencies

Download Jakarta Commons FileUpload-based upload support jar package

Commons-fileupload commons-fileupload 1.4

If you use idea, be sure to import the package manually.

2-2. Configure spring.xml injection CommonsMultipartResolver file upload parser 2-3, file upload

2-3-1, single file upload

2-3-1-1. The method of writing controller

/ * * upload based on springmvc MultiPartResolver files * @ param desc * @ param multipartFile * @ return * @ throws IOException * / @ PostMapping ("/ upload01") public String upload01 (String desc, @ RequestParam ("myfile") MultipartFile multipartFile) throws IOException {System.out.println (desc); System.out.println (multipartFile.getOriginalFilename ()); String path = "d:\\ img\" + multipartFile.getOriginalFilename (); File file = new File (path); multipartFile.transferTo (file) Return "success";}

2-3-1-2, View layer

File description:

File:

2-3-2, multiple file upload

2-3-2-1. The method of writing controller

/ * * upload multiple files based on springmvc MultiPartResolver * @ param desc * @ param myfile * @ return * @ throws IOException * / @ PostMapping ("/ upload02") public String upload02 (String desc,MultipartFile [] myfile) throws IOException {for (MultipartFile multipartFile: myfile) {System.out.println (desc); System.out.println (multipartFile.getOriginalFilename ()); String path = "d:\ img\" + multipartFile.getOriginalFilename () File file = new File (path); multipartFile.transferTo (file);} return "success";}

2-3-2-2, View layer

View layer We can control whether files uploaded by file are multi-selected. We can use mutiple= "mutiple" in H6 if the attribute and value are equal, you can omit the value, and then set the accept property, which can be filtered automatically when the user selects it. For example, the following code only shows files of picture type.

File description:

File:

2-3-3. Upload files in batches through multi-threading

In the above example, multi-file upload is used. Although files can be read and uploaded one by one using for, in some scenarios, the efficiency is greatly reduced. In order to improve the efficiency of uploading, we can use multi-thread to upload.

2-3-3-4. The method of writing controller

/ * * multifile upload based on springmvc MultiPartResolver-multithreading * @ param desc * @ param myfile * @ return * @ throws IOException * / @ PostMapping ("/ upload03") public String upload03 (String desc,MultipartFile [] myfile) throws IOException, InterruptedException {System.out.println (desc) For (MultipartFile multipartFile: myfile) {/ / declare thread Thread thread = new Thread (()-> {System.out.println (multipartFile.getOriginalFilename ()); String path = "d:\ img\" + multipartFile.getOriginalFilename (); File file = new File (path); try {multipartFile.transferTo (file)) } catch (IOException e) {e.printStackTrace ();}}); thread.start (); / start the thread thread.join (); / / Let the child thread finish executing and then execute the main thread} return "success" } this is the end of the article on "how to upload and download SpringMVC based on annotations". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to upload and download SpringMVC based on annotations". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report