spring boot 返回文件流_springboot返回文件流-CSDN博客

所需依赖

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency>

完整的Controller代码

import org.springframework.core.io.InputStreamResource;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream; @Controllerpublic class FileDownloadController {     @GetMapping("/download")    @ResponseBody    public ResponseEntity<InputStreamResource> downloadFile() throws IOException {        File file = new File("实际的文件路径");        InputStream inputStream = new FileInputStream(file);        InputStreamResource resource = new InputStreamResource(inputStream);         HttpHeaders headers = new HttpHeaders();        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=实际的文件名");         return ResponseEntity.ok()                .headers(headers)                .contentLength(file.length())                .contentType(MediaType.APPLICATION_OCTET_STREAM)                .body(resource);    }}

原网址: 访问
创建于: 2024-12-12 09:39:42
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论