Spring Boot提供了一些方便的类库,可以用于上传和下载文件。下面是一个示例代码,可以实现文件上传和下载功能。

上传文件:

@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
    try {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 创建文件存储路径
        Path filePath = Paths.get(UPLOAD_DIR, fileName);
        // 将文件存储到磁盘
        Files.write(filePath, file.getBytes());
        // 返回上传成功的消息
        return ResponseEntity.ok("上传成功!");
    } catch (IOException e) {
        e.printStackTrace();
        // 返回上传失败的消息
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败!");
    }
}

下载文件:

@GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
    try {
        // 获取文件路径
        Path filePath = Paths.get(UPLOAD_DIR, fileName);
        // 创建资源对象
        Resource resource = new UrlResource(filePath.toUri());
        // 判断文件是否存在且可读
        if (resource.exists() && resource.isReadable()) {
            // 设置HTTP头信息
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            // 返回资源对象
            return ResponseEntity.ok().headers(headers).body(resource);
        } else {
            // 返回404错误
            return ResponseEntity.notFound().build();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        // 返回500错误
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

其中,UPLOAD_DIR是文件上传的目录,可以在配置文件中配置。例如:

spring:
  servlet:
    multipart:
      enabled: true
      file-size-threshold: 2MB
      max-file-size: 10MB
      max-request-size: 50MB
  resources:
    static-locations: file:/path/to/upload/dir/

在上面的配置中,设置了上传文件的大小限制和上传文件存储的目录

springboot上传下载文件

原文地址: http://www.cveoy.top/t/topic/fUJa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录