溫馨提示×

SpringBoot中怎么實現文件上傳和下載功能

小億
250
2024-04-18 16:05:18
欄目: 編程語言

在SpringBoot中實現文件上傳和下載功能,通常需要借助Spring的MultipartFile對象來處理文件上傳,同時使用OutputStream對象來處理文件下載。以下是一個簡單的示例代碼:

  1. 文件上傳:
@RestController
public class FileController {

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 獲取文件名
            String fileName = file.getOriginalFilename();
            // 文件保存路徑
            String filePath = "C:/upload/";
            // 文件保存操作
            file.transferTo(new File(filePath + fileName));
            return "File uploaded successfully!";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload file.";
        }
    }

}
  1. 文件下載:
@RestController
public class FileController {

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String fileName) {
        // 文件路徑
        String filePath = "C:/upload/";
        // 獲取文件對象
        Resource file = new FileSystemResource(filePath + fileName);
        
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(file);
    }

}

在以上代碼示例中,文件上傳時,通過@RequestParam注解獲取前端傳遞的文件對象,然后使用transferTo方法保存文件到指定路徑。文件下載時,通過ResponseEntity返回文件資源對象,并設置響應頭信息,以實現文件下載功能。

需要注意的是,以上代碼只是一個簡單的示例,實際開發中可能需要加入更多的邏輯來處理文件上傳和下載,比如文件格式驗證、文件大小限制等。

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