溫馨提示×

springboot上傳下載功能怎么實現

小億
153
2023-11-06 22:42:06
欄目: 編程語言

在Spring Boot中,可以使用MultipartFile接口來實現文件上傳功能,使用ResponseEntity來實現文件下載功能。

文件上傳功能的實現步驟如下:

  1. 在Controller中添加一個處理文件上傳的方法,并使用@RequestParam注解來接收上傳的文件參數。
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
    // 處理文件上傳邏輯
    // ...
    return "上傳成功";
}
  1. 在application.properties或application.yml配置文件中添加文件上傳相關的配置。
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  1. 在前端頁面中添加一個文件上傳表單,并設置enctype屬性為multipart/form-data。
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">上傳</button>
</form>

文件下載功能的實現步驟如下:

  1. 在Controller中添加一個處理文件下載的方法,并使用PathVariable注解來接收文件名參數。
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
    // 獲取文件路徑
    String filePath = "path/to/file/" + filename;
    // 創建文件資源對象
    Resource fileResource = new FileSystemResource(filePath);
    
    // 設置響應頭
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
    
    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(fileResource.contentLength())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(fileResource);
}
  1. 在前端頁面中添加一個下載按鈕,并設置對應的下載鏈接。
<a th:href="@{/download/filename}" download>下載</a>

其中,filename為要下載的文件名。

以上就是Spring Boot中實現文件上傳下載功能的基本步驟。具體實現根據具體需求可能會有所不同,可以根據需要進行調整。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女