In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces SpringBoot how to achieve file upload function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
Classic file upload
The server usually reads the file information in the request, then changes the name to save it under the temporary path of the server, and finally saves it to the server disk. This time, the demo is built with thymeleaf, so it is necessary to introduce the thymeleaf dependent library.
Org.springframework.boot spring-boot-starter-thymeleaf 2.5.5
If you are using a gradle-built project, you need to modify the build.gradle file:
Compile 'org.springframework.boot:spring-boot-starter-thymeleaf:2.5.5'
Create a new Action class to handle uploaded files:
@ RestController@RequestMapping ("/ upload/*") public class UploadAction {@ PostMapping ("/ file") public Object uploadHandler (HttpServletRequest request, String title, MultipartFile file) {Map resultMap = new LinkedHashMap (); resultMap.put ("title", title); resultMap.put ("fileName", file.getName ()); / / file name resultMap.put ("originalFilename", file.getOriginalFilename ()) / / original name resultMap.put ("content-type", file.getContentType ()); / / File type resultMap.put ("fileSize", file.getSize () / 1024 + "K") / / File size try {/ / Save file String uploadedFilePath = saveFile (request, file.getInputStream (), file.getOriginalFilename () .substring (file.getOriginalFilename (). LastIndexOf (".") + 1); resultMap.put ("uploadedFilePath", uploadedFilePath) / / File size} catch (IOException e) {System.err.println ("error-path: / upload/file, message:" + e.getMessage ());} return resultMap } / * Save uploaded files to local server * * @ param request HttpServletRequest * @ param input input stream * @ param ext file extension * @ return file path * @ throws IOException * / public String saveFile (HttpServletRequest request, InputStream input, String ext) throws IOException {String realPath = request.getServletContext () .getRealPath ("/ upload/file/") / / get the real path to the server File file = new File (realPath); if (! file.getParentFile (). Exists ()) {/ / directory does not exist file.mkdirs (); / / create a multi-level directory} String filePath = realPath + UUID.randomUUID () + "." + ext; / / the file output stream OutputStream out = new FileOutputStream (filePath) Byte [] data = new byte [2048]; / buffer array 2KB int len = 0; / / read byte length while ((len = input.read (data))! =-1) {out.write (data, 0, len); / / File write to disk} if (input! = null) {input.close () } out.close (); return filePath;}}
Create a new templates folder under the resources directory and create an index.html file in it to display as the home page of the project.
File upload test title:
File:
Start the project and visit directly: http://localhost:8080/ will go to the index.html page.
Click the upload button and the file will be saved to the server disk:
SpringBoot simplifies the processing of uploaded files
SpringBoot integrates the FileUpload component to avoid directly manipulating the IO stream when saving the file, and specify the limit parameters for file upload by configuring the file. Modify the application.yml file:
Server: port: 8080spring: servlet: multipart: enabled: true # enable file upload max-file-size: 1MB # maximum limit for single file upload max-request-size: 10MB # maximum file upload file-size-threshold: 10KB # write to disk location: / # temporary file storage location when uploading a file
Modify UploadAction and use the transferTo method of the MultipartFile class to save the uploaded file.
@ RestController@RequestMapping ("/ upload/*") public class UploadAction {@ PostMapping ("/ file") public Object uploadHandler (HttpServletRequest request, String title, MultipartFile file) {Map resultMap = new LinkedHashMap (); resultMap.put ("title", title); resultMap.put ("fileName", file.getName ()); / / file name resultMap.put ("originalFilename", file.getOriginalFilename ()) / / original name resultMap.put ("content-type", file.getContentType ()); / / File type resultMap.put ("fileSize", file.getSize () / 1024 + "K"); / / File size try {/ / Save file String etc = file.getOriginalFilename (). Substring (file.getOriginalFilename (). LastIndexOf (".") + 1) String serverPath = request.getScheme () + ": / /" + request.getServerName () + ":" + request.getServerPort () + request.getContextPath () + "/ file/upload/"; String fileName = UUID.randomUUID () + "." + etc; resultMap.put ("filePath", serverPath + fileName) / / File address (server access address) / / File saveFile = new File (request.getServletContext (). GetRealPath ("/ file/upload/") + fileName) under the real path; if (! saveFile.getParentFile (). Exists ()) {/ / directory does not exist, create a directory saveFile.mkdirs () } file.transferTo (saveFile); / / Save upload file} catch (IOException e) {System.err.println ("error-path: / upload/file, message:" + e.getMessage ());} return resultMap;}}
Visit: http://localhost:8080/
Click the upload button:
Visit filePath on the browser to preview the uploaded file:
Thank you for reading this article carefully. I hope the article "how to realize the file upload function of SpringBoot" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.