使用Spring Boot REST实现文件的上传/下载

x33g5p2x  于2022-10-04 转载在 Spring  
字(4.1k)|赞(0)|评价(0)|浏览(707)

在本教程中,我们将学习如何使用Spring Boot REST服务来实现上传和下载文件。为此,我们将使用Swagger UI与REST控制器进行交互。

设置你的Spring Boot项目

首先,添加一个Spring Boot应用程序类来引导你的项目。

  1. @SpringBootApplication
  2. public class DemoApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(DemoApplication.class, args);
  5. }
  6. }

接下来,我们将编码我们的主控制器类,它将处理文件的上传和下载。

  1. @RestController public class RestFilesController {
  2. private final Logger logger = LoggerFactory.getLogger(RestFilesController.class);
  3. // Save the uploaded file to this folder
  4. private static String UPLOADED_FOLDER = "/tmp/uploads/";
  5. // Single File upload
  6. @PostMapping(value = "/rest/upload", consumes = {
  7. "multipart/form-data"
  8. })
  9. @Operation(summary = "Upload a single File")
  10. public ResponseEntity < ? > uploadFile(@RequestParam("file") MultipartFile uploadfile) {
  11. logger.debug("Single file upload!");
  12. if (uploadfile.isEmpty()) {
  13. return new ResponseEntity("You must select a file!", HttpStatus.OK);
  14. }
  15. try {
  16. saveUploadedFiles(Arrays.asList(uploadfile));
  17. } catch (IOException e) {
  18. return new ResponseEntity < > (HttpStatus.BAD_REQUEST);
  19. }
  20. return new ResponseEntity("Successfully uploaded - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK);
  21. }
  22. // Multiple File upload
  23. @PostMapping(value = "/rest/multipleupload", consumes = {
  24. "multipart/form-data"
  25. })
  26. @Operation(summary = "Upload multiple Files")
  27. public ResponseEntity uploadFiles(@RequestPart String metaData, @RequestPart(required = true) MultipartFile[] uploadfiles) {
  28. String uploadedFileName = Arrays.stream(uploadfiles).map(x -> x.getOriginalFilename()).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
  29. if (StringUtils.isEmpty(uploadedFileName)) {
  30. return new ResponseEntity("please select a file!", HttpStatus.OK);
  31. }
  32. try {
  33. saveUploadedFiles(Arrays.asList(uploadfiles));
  34. } catch (IOException e) {
  35. return new ResponseEntity < > (HttpStatus.BAD_REQUEST);
  36. }
  37. return new ResponseEntity("Successfully uploaded - " + uploadedFileName, HttpStatus.OK);
  38. }
  39. // Single File download
  40. @RequestMapping(path = "/rest/download", method = RequestMethod.GET)
  41. @Operation(summary = "Download a File")
  42. public ResponseEntity < Resource > downloadFile(String fileName) throws IOException {
  43. File file = new File(UPLOADED_FOLDER + fileName);
  44. HttpHeaders headers = new HttpHeaders();
  45. headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
  46. headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
  47. headers.add("Pragma", "no-cache");
  48. headers.add("Expires", "0");
  49. Path path = Paths.get(UPLOADED_FOLDER + fileName);
  50. ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
  51. return ResponseEntity.ok()
  52. .headers(headers)
  53. .contentLength(file.length())
  54. .contentType(MediaType.APPLICATION_OCTET_STREAM)
  55. .body(resource);
  56. }
  57. // save file
  58. private void saveUploadedFiles(List < MultipartFile > files) throws IOException {
  59. File folder = new File(UPLOADED_FOLDER);
  60. if (!folder.exists()) {
  61. folder.mkdir();
  62. }
  63. for (MultipartFile file: files) {
  64. if (file.isEmpty()) {
  65. continue;
  66. // next pls
  67. }
  68. byte[] bytes = file.getBytes();
  69. Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
  70. Files.write(path, bytes);
  71. }
  72. }
  73. }

我们的控制器类包括三个主要方法。

uploadFile: 处理单个文件的上传。
uploadFiles:处理多个文件的上传。
downloadFile:你可以用来下载一个文件。

所有的文件都上传到UPLOADED_FOLDER路径中。

接下来,为了构建你的项目,确保你有starter-web和springdoc-openapi-ui两个依赖项。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springdoc</groupId>
  7. <artifactId>springdoc-openapi-ui</artifactId>
  8. <version>1.6.6</version>
  9. </dependency>

我们将使用后一个依赖项来测试我们的Rest Controller与Swagger UI。

测试Rest Controller

接下来,构建并运行应用程序

  1. mvn install spring-boot:run

最后,在http://localhost:8080/swagger-ui/index.html接触到Swagger的UI,在那里你可以测试应用程序。

接下来,选择你想测试的方法并 "试一试"。例如,让我们测试一下文件上传。

拿起你要上传的文件,点击 "执行"。为了验证该文件是否可用,检查上传路径,看文件是否在那里。

  1. $ ls /tmp/uploads/
  2. swagger1.png

最后,使用适当的REST HTTP GET测试文件下载。

点击 "执行 "并验证下载是否在你的浏览器上开始。太好了!你刚刚成功地用Spring Boot上传/下载了文件。

本教程的源代码:https://github.com/fmarchioni/masterspringboot/tree/master/rest/upload-download

是Jakarta或Java EE用户吗?那么请查看本教程,学习how to upload and download files with JAX-RS

相关文章