java - 从 Spring Boot Rest 服务下载文件

标签 java spring rest

我正在尝试从 Spring Boot Rest 服务下载文件。

@RequestMapping(path="/downloadFile",method=RequestMethod.GET)
    @Consumes(MediaType.APPLICATION_JSON_VALUE)
    public  ResponseEntity<InputStreamReader> downloadDocument(
                String acquistionId,
                String fileType,
                Integer expressVfId) throws IOException {
        File file2Upload = new File("C:\\Users\\admin\\Desktop\\bkp\\1.rtf");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        InputStreamReader i = new InputStreamReader(new FileInputStream(file2Upload));
        System.out.println("The length of the file is : "+file2Upload.length());

        return ResponseEntity.ok().headers(headers).contentLength(file2Upload.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(i);
        }

当我尝试从浏览器下载文件时,它会开始下载,但总是失败。导致下载失败的服务有什么问题吗?

最佳答案

选项 1 使用 InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Option2 正如 InputStreamResource 的文档所建议的那样 - 使用 ByteArrayResource :

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

关于java - 从 Spring Boot Rest 服务下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35680932/

相关文章:

java - XML 或 XUL 是 Java GUI 构建的 future 吗?

java - bean 类中的属性值在构造函数中为 null

json - 关于 ember cli 如何获取 JSON 响应的体面教程

asp.net-mvc - 构建与数据格式分离的 ASP.NET MVC REST API 代码的最佳方法?

java - 使用 Spring 实现工厂方法

java - 获取通知访问授予状态

Java 应用程序在未从命令行运行时挂起

java - 事务性保存而不调用更新方法

spring - 没有命名 EntityManager 的持久性提供程序

php - 为 PHP 网络应用程序选择正确的 OAuth2 授权类型