springboot学习第13期 - 文件上传下载

89 阅读1分钟

在 Spring Boot 中实现文件上传非常简单,核心是使用 MultipartFile 接收前端上传的文件。

文件上传下载 - 基础

上传单文件并保存到本地目录。

@Slf4j
@RestController
@RequestMapping("/api/files")
public class FileController {

    @Value("${upload.path:D:/upload/}")  // 末尾加不加斜杠都行
    private Path uploadPath;

    @PostConstruct
    public void init() throws IOException {
        Files.createDirectories(uploadPath);
    }

    @PostMapping("/upload")
    public void upload(@RequestParam MultipartFile file) {
        log.info("Received file: " + file.getOriginalFilename());

        try {
            Path dest = uploadPath.resolve(file.getOriginalFilename());
            file.transferTo(dest);
            log.info("File uploaded to: " + dest);
        } catch (IOException e) {
            throw new RuntimeException("Failed to upload file", e);
        }

    }

    @GetMapping("/download/{filename}")
    public ResponseEntity<Resource> download(@PathVariable String filename) throws IOException {
        log.info("filename: {}", filename);
        Path filePath = uploadPath.resolve(filename);
        log.info("filePath: {}", filePath);
        Resource resource = new UrlResource(filePath.toUri());

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);   // Spring 会自动把 Resource 写回客户端
    }
}

相关配置:

spring.servlet.multipart.max-file-size=200MB  # 单个文件最大限制
spring.servlet.multipart.max-request-size=200MB  # 一次请求最大限制,因为可以上传多个文件

建议不要再用 java.io.File 类,它几乎被淘汰。

上传多个文件

改成集合类型即可:List

@Slf4j
@RestController
@RequestMapping("/api/files")
public class FileController {

    @Value("${upload.path:D:/upload}")
    private Path uploadPath;

    @PostConstruct
    public void init() throws IOException {
        Files.createDirectories(uploadPath);
    }

    @PostMapping("/upload")
    public void upload(@RequestParam List<MultipartFile> files) {
        log.info("Received file: " + files.size());

        try {
            for (MultipartFile file : files) {
                Path dest = uploadPath.resolve(file.getOriginalFilename());
                file.transferTo(dest);
                log.info("File uploaded to: " + dest);
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to upload file", e);
        }
    }

}