温馨提示×

SpringBoot怎么实现文件上传和下载

小亿
88
2024-04-09 16:36:43
栏目: 编程语言

在Spring Boot中实现文件上传和下载可以通过以下步骤来实现:

  1. 文件上传: 使用Spring Boot的MultipartFile类来处理文件上传。首先在Controller中创建一个POST接口来处理文件上传请求:
@PostMapping("/upload")
public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) {
    // 保存文件到本地或者存储到数据库
    // 返回成功或者失败的消息
}
  1. 文件下载: 创建一个GET接口来处理文件下载请求,并在Controller中编写如下代码:
@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
    // 从本地或者数据库中获取文件
    Resource resource = fileStorageService.loadFileAsResource(fileName);

    // 设置响应头
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);
}

要实现文件上传和下载,还需要创建一个文件存储服务类(FileStorageService),并在该类中编写文件保存和加载的逻辑。例如,可以使用以下方法保存上传的文件到本地:

@Service
public class FileStorageService {

    @Value("${file.upload-dir}")
    private String uploadDir;

    public void storeFile(MultipartFile file) {
        Path filePath = Paths.get(uploadDir).resolve(file.getOriginalFilename());
        try {
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new FileNotFoundException("File not found " + fileName);
            }
        } catch (MalformedURLException | FileNotFoundException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}

在上述示例中,file.upload-dir是配置文件中配置的文件上传目录,可以在application.properties文件中配置:

file.upload-dir=/path/to/upload/dir

这样就可以在Spring Boot中实现文件上传和下载功能。

0