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

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

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

设置你的Spring Boot项目

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

@SpringBootApplication

public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }

   
}

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

@RestController public class RestFilesController {
   private final Logger logger = LoggerFactory.getLogger(RestFilesController.class);

   // Save the uploaded file to this folder
   private static String UPLOADED_FOLDER = "/tmp/uploads/";

   // Single File upload   
   @PostMapping(value = "/rest/upload", consumes = {
      "multipart/form-data"
   })
   @Operation(summary = "Upload a single File")
   public ResponseEntity < ? > uploadFile(@RequestParam("file") MultipartFile uploadfile) {
      logger.debug("Single file upload!");
      if (uploadfile.isEmpty()) {
         return new ResponseEntity("You must select a file!", HttpStatus.OK);
      }
      try {
         saveUploadedFiles(Arrays.asList(uploadfile));
      } catch (IOException e) {
         return new ResponseEntity < > (HttpStatus.BAD_REQUEST);
      }
      return new ResponseEntity("Successfully uploaded - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK);
   }

   // Multiple File upload   
   @PostMapping(value = "/rest/multipleupload", consumes = {
      "multipart/form-data"
   })
   @Operation(summary = "Upload multiple Files")

   public ResponseEntity uploadFiles(@RequestPart String metaData, @RequestPart(required = true) MultipartFile[] uploadfiles) {

      String uploadedFileName = Arrays.stream(uploadfiles).map(x -> x.getOriginalFilename()).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
      if (StringUtils.isEmpty(uploadedFileName)) {
         return new ResponseEntity("please select a file!", HttpStatus.OK);
      }
      try {
         saveUploadedFiles(Arrays.asList(uploadfiles));
      } catch (IOException e) {
         return new ResponseEntity < > (HttpStatus.BAD_REQUEST);
      }
      return new ResponseEntity("Successfully uploaded - " + uploadedFileName, HttpStatus.OK);
   }

   // Single File download
   @RequestMapping(path = "/rest/download", method = RequestMethod.GET)
   @Operation(summary = "Download a File")

   public ResponseEntity < Resource > downloadFile(String fileName) throws IOException {
      File file = new File(UPLOADED_FOLDER + fileName);
      HttpHeaders headers = new HttpHeaders();
      headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
      headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
      headers.add("Pragma", "no-cache");
      headers.add("Expires", "0");
      Path path = Paths.get(UPLOADED_FOLDER + fileName);

      ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

      return ResponseEntity.ok()
         .headers(headers)
         .contentLength(file.length())
         .contentType(MediaType.APPLICATION_OCTET_STREAM)
         .body(resource);

   }

   // save file
   private void saveUploadedFiles(List < MultipartFile > files) throws IOException {
      File folder = new File(UPLOADED_FOLDER);
      if (!folder.exists()) {
         folder.mkdir();
      }
      for (MultipartFile file: files) {
         if (file.isEmpty()) {
            continue;
            // next pls
         }
         byte[] bytes = file.getBytes();
         Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
         Files.write(path, bytes);
      }
   }

}

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

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

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

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

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-ui</artifactId>
  <version>1.6.6</version>
</dependency>

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

测试Rest Controller

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

mvn install spring-boot:run

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

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

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

$ ls /tmp/uploads/

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

相关文章

微信公众号

最新文章

更多