当前位置: 首页 > article >正文

springboot文件上传下载

基于ResponseEntity的下载响应

SpringBoot中,ResponseEntity类型可以精确控制HTTP响应,为文件下载提供完善的HTTP头信息。

@RestController
@RequestMapping("/api/download")
public class FileDownloadController {@GetMapping("/file/{fileName:.+}")public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) {try {Path filePath = Paths.get("uploads/" + fileName);byte[] data = Files.readAllBytes(filePath);HttpHeaders headers = new HttpHeaders();headers.setContentDisposition(ContentDisposition.attachment().filename(fileName, StandardCharsets.UTF_8).build());headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentLength(data.length);return new ResponseEntity<>(data, headers, HttpStatus.OK);} catch (IOException e) {return ResponseEntity.notFound().build();}}@GetMapping("/dynamic-pdf")public ResponseEntity<byte[]> generatePdf() {// 假设这里生成了PDF文件的字节数组byte[] pdfContent = generatePdfService.createPdf();HttpHeaders headers = new HttpHeaders();headers.setContentDisposition(ContentDisposition.attachment().filename("generated-report.pdf").build());headers.setContentType(MediaType.APPLICATION_PDF);return new ResponseEntity<>(pdfContent, headers, HttpStatus.OK);}
}

优势

  • • 完全控制HTTP响应和头信息

  • • 适合各种资源类型的下载

  • • 支持动态生成的文件下载

适用场景

  • • 需要精确控制HTTP响应的场景

  • • 动态生成的文件下载

  • • 自定义缓存策略的文件服务

 基于Servlet的原生文件操作

在某些情况下,可能需要使用原生Servlet API进行更底层的文件操作。

@WebServlet("/servlet/download")
public class FileDownloadServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String fileName = request.getParameter("file");if (fileName == null || fileName.isEmpty()) {response.sendError(HttpServletResponse.SC_BAD_REQUEST);return;}File file = new File("uploads/" + fileName);if (!file.exists()) {response.sendError(HttpServletResponse.SC_NOT_FOUND);return;}// 设置响应头response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment; filename="" + fileName + """);response.setContentLength((int) file.length());// 写入文件内容try (FileInputStream input = new FileInputStream(file);ServletOutputStream output = response.getOutputStream()) {byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = input.read(buffer)) != -1) {output.write(buffer, 0, bytesRead);}}}
}

要在SpringBoot中启用Servlet:

@SpringBootApplication
@ServletComponentScan  // 扫描Servlet组件
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

优势

  • • 对文件流操作有最大的控制权

  • • 可以实现渐进式下载和流式处理

  • • 对内存使用更加高效

适用场景

  • • 大文件处理

  • • 需要细粒度控制IO操作

  • • 与遗留Servlet系统集成

云存储服务SDK集成

对于生产环境,将文件存储在专业的存储服务中通常是更好的选择,如AWS S3、阿里云OSS、七牛云等。

<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.1</version>
</dependency>
@Configuration
public class OssConfig {@Value("${aliyun.oss.endpoint}")private String endpoint;@Value("${aliyun.oss.accessKeyId}")private String accessKeyId;@Value("${aliyun.oss.accessKeySecret}")private String accessKeySecret;@Value("${aliyun.oss.bucketName}")private String bucketName;@Beanpublic OSS ossClient() {return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);}@Beanpublic String bucketName() {return bucketName;}
}
@RestController
@RequestMapping("/api/oss")
public class OssFileController {@Autowiredprivate OSS ossClient;@Value("${aliyun.oss.bucketName}")private String bucketName;@PostMapping("/upload")public String uploadToOss(@RequestParam("file") MultipartFile file) {if (file.isEmpty()) {return "请选择文件";}try {String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();// 上传文件流ossClient.putObject(bucketName, fileName, file.getInputStream());// 生成访问URLDate expiration = new Date(System.currentTimeMillis() + 3600 * 1000);URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);return "文件上传成功,访问URL: " + url.toString();} catch (Exception e) {e.printStackTrace();return "文件上传失败: " + e.getMessage();}}@GetMapping("/download")public ResponseEntity<byte[]> downloadFromOss(@RequestParam("key") String objectKey) {try {// 获取文件OSSObject ossObject = ossClient.getObject(bucketName, objectKey);// 读取文件内容try (InputStream is = ossObject.getObjectContent()) {byte[] content = IOUtils.toByteArray(is);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentDisposition(ContentDisposition.attachment().filename(objectKey).build());return new ResponseEntity<>(content, headers, HttpStatus.OK);}} catch (Exception e) {e.printStackTrace();return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();}}
}

 Spring Resource抽象 - 统一资源访问

Spring的Resource抽象提供了对不同来源资源的统一访问方式,非常适合文件下载场景。

@RestController
@RequestMapping("/api/resources")
public class ResourceDownloadController {@GetMapping("/download/{fileName:.+}")public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {try {// 创建文件资源Path filePath = Paths.get("uploads/" + fileName);Resource resource = new UrlResource(filePath.toUri());// 检查资源是否存在if (resource.exists()) {return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="" + resource.getFilename() + """).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);} else {return ResponseEntity.notFound().build();}} catch (Exception e) {return ResponseEntity.internalServerError().build();}}
}

优势

  • • 提供统一的资源抽象,易于切换资源来源

  • • 与Spring生态系统无缝集成

  • • 支持多种协议和位置的资源

适用场景

  • • 需要从多种来源提供下载的场景

  • • RESTful API文件下载

  • • 动态生成的资源下载

 Apache Commons FileUpload - 灵活的文件上传库

虽然SpringBoot内部已集成文件上传功能,但在某些场景下,可能需要Apache Commons FileUpload提供的更多高级特性。

<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.5</version>
</dependency>
@Bean
public CommonsMultipartResolver multipartResolver() {CommonsMultipartResolver resolver = new CommonsMultipartResolver();resolver.setDefaultEncoding("UTF-8");resolver.setMaxUploadSize(10485760); // 10MBresolver.setMaxUploadSizePerFile(2097152); // 2MBreturn resolver;
}
@RestController
@RequestMapping("/api/commons")
public class CommonsFileUploadController {@PostMapping("/upload")public String handleFileUpload(HttpServletRequest request) throws Exception {// 判断是否包含文件上传boolean isMultipart = ServletFileUpload.isMultipartContent(request);if (!isMultipart) {return "不是有效的文件上传请求";}// 创建上传器DiskFileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);// 解析请求List<FileItem> items = upload.parseRequest(request);for (FileItem item : items) {if (!item.isFormField()) {// 处理文件项String fileName = FilenameUtils.getName(item.getName());File uploadedFile = new File("uploads/" + fileName);item.write(uploadedFile);return "文件上传成功: " + fileName;}}return "未找到要上传的文件";}
}

优势

  • • 提供更细粒度的控制

  • • 支持文件上传进度监控

  • • 可自定义文件存储策略

适用场景

  • • 需要对上传过程进行细粒度控制

  • • 大文件上传并监控进度

  • • 遗留系统集成

http://www.lryc.cn/news/2395065.html

相关文章:

  • webpack CDN打包优化
  • ARM内核一览
  • Rust 和 Python 如何混合使用
  • 台式电脑CPU天梯图_2025年台式电脑CPU天梯图
  • 2025年渗透测试面试题总结-匿名[校招]安全服务工程师(题目+回答)
  • Deseq2:MAG相对丰度差异检验
  • CTFHub-RCE 命令注入-过滤目录分隔符
  • 从零开始的数据结构教程(七) 回溯算法
  • CentOS-stream-9 Zabbix的安装与配置
  • 开源是什么?我们为什么要开源?
  • 【unity游戏开发——编辑器扩展】EditorApplication公共类处理编辑器生命周期事件、播放模式控制以及各种编辑器状态查询
  • elasticsearch低频字段优化
  • React---day3
  • PyCharm接入DeepSeek,实现高效AI编程
  • 前端面经 get和post区别
  • CTFSHOW-WEB-36D杯
  • MySQL connection close 后, mysql server上的行为是什么
  • RabbitMQ vs MQTT:深入比较与最新发展
  • 金砖国家人工智能高级别论坛在巴西召开,华院计算应邀出席并发表主题演讲
  • 【KWDB 创作者计划】_再热垃圾发电汽轮机仿真与监控系统:KaiwuDB 批量插入10万条数据性能优化实践
  • CentOS 7 安装docker缺少slirp4netnsy依赖解决方案
  • Android第十一次面试多线程篇
  • 安全,稳定可靠的政企即时通讯数字化平台
  • craw4ai 抓取实时信息,与 mt4外行行情结合实时交易,基本面来觉得趋势方向,搞一个外汇交易策略
  • Linux之守护进程
  • LiquiGen流体导入UE
  • 使用react进行用户管理系统
  • SpringBoot的java应用中,慢sql会导致CPU暴增吗
  • Ubuntu下编译mininim游戏全攻略
  • uniapp uni-id Error: Invalid password secret