乐闻世界logo
搜索文章和话题

如何在Spring Boot应用中实现文件上传和下载功能?

1 个月前提问
1 个月前修改
浏览次数10

1个答案

1

实现文件上传

在Spring Boot中实现文件上传功能,通常会使用Spring MVC的MultipartFile接口。以下步骤和示例代码将指导如何实现:

  1. 依赖添加:首先确保在pom.xml中加入Spring Boot的Web依赖。

    xml
    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  2. 控制器编写:创建一个控制器来处理文件上传的HTTP请求。

    java
    import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { try { String fileName = file.getOriginalFilename(); // 文件保存逻辑 file.transferTo(new File("path/to/destination/" + fileName)); return "文件上传成功"; } catch (Exception e) { return "文件上传失败: " + e.getMessage(); } } }
  3. 配置文件大小限制:在application.propertiesapplication.yml中设置最大文件大小和请求大小。

    properties
    # application.properties spring.servlet.multipart.max-file-size=2MB spring.servlet.multipart.max-request-size=2MB

实现文件下载

文件下载功能可以通过返回一个Resource的控制器实现:

  1. 控制器编写:创建一个控制器来处理文件下载的HTTP请求。

    java
    import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import java.nio.file.Path; import java.nio.file.Paths; @RestController public class FileDownloadController { @GetMapping("/download") public ResponseEntity<Resource> downloadFile(@RequestParam String filename) { try { Path file = Paths.get("path/to/destination").resolve(filename); Resource resource = new UrlResource(file.toUri()); if (resource.exists() || resource.isReadable()) { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } else { throw new RuntimeException("无法读取文件"); } } catch (Exception e) { throw new RuntimeException("错误: " + e.getMessage()); } } }
  2. 异常处理:处理文件不存在或文件不可读的情况,确保用户得到正确的反馈。

以上是如何在Spring Boot应用程序中添加文件上传和下载功能的基本步骤和示例代码。这些功能需结合具体的业务需求进行调整和优化,例如添加安全性检查(防止恶意文件上传)、使用数据库管理文件元数据等。

2024年8月7日 22:10 回复

你的答案