Spring REST / Swagger / Postman-损坏/空白文件正在下载 [英] Spring REST / Swagger / Postman - Damaged/Blank File being dowloaded

查看:129
本文介绍了Spring REST / Swagger / Postman-损坏/空白文件正在下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照这篇帖子中的功能进行了介绍:客户端现在可以下载文件(即csv,pdf和zip)。

I followed this post for the functionality: client can download a file(ie, csv,pdf and zip) as of now.

但是我得到的是空白的pdf或尝试使用zip文件时,它已损坏。只有CSV可以正常工作

我已经检查了标头,所有内容似乎都符合标准。我什至不使用 application / octet-stream,而不使用pdf的 application / pdf,使用csv的 application / csv,使用zip的 application / zip,只是为了避免客户端出现任何问题。我正在使用swagger 2.4测试我的api。这是我的代码。

I have checked the headers, everything seems as per the standard. I am not even using "application/octet-stream" and using "application/pdf" for pdf, "application/csv" for csv and "application/zip" for zip just to avoid any issue with client. I am using swagger 2.4 to test my apis. Here is my code.

@CrossOrigin
@Controller
public class ReportRestController {


@Autowired
ReportService reportService;

@Value("${report.temp.directory}") // used for storing file in local
private String reportLocation;

@ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "Authorization", required = true, dataType = "string", paramType = "header"),
        @ApiImplicitParam(name = "Auth-Provider", value = "Auth-Provider", required = true, dataType = "string", paramType = "header"),})
@RequestMapping(value = "/report/{type}/{format}", method = RequestMethod.POST)
public void getList(@RequestHeader(value = "UserId", required = false) Long userId,
        @RequestHeader(value = "TeamId", required = false) Long teamId,
        @RequestHeader(value = "CustomerId", required = true) Long customerId,
        @PathVariable("type") String type, @PathVariable("format") String formate,
        @RequestBody ReportRequestObj reportobj, HttpServletResponse response) {

    String filename = reportService.getReport(customerId, userId, teamId, type, formate, reportobj);
    Path pathfile = Paths.get(reportLocation, filename);
    File file = pathfile.toFile();
    if (file.exists()) {
        String fileExtension = FilenameUtils.getExtension(filename);
        if(CommonConstants.CSV.equals(fileExtension)){
            response.setContentType("application/csv");
        }else if(CommonConstants.PDF.equals(fileExtension)){
            response.setContentType("application/pdf");
        }else if(CommonConstants.ZIP.equals(fileExtension)){
            response.setContentType("application/zip");
        }
        response.addHeader("Content-Disposition", "attachment; filename=" + filename);
        response.setContentLength((int) file.length());
        response.setHeader("Content-Transfer-Encoding", "binary");
        try(FileInputStream fileInputStream = new FileInputStream(file)) {
            IOUtils.copy(fileInputStream,response.getOutputStream());
            response.getOutputStream().flush();
            //response.flushBuffer();
        } catch (IOException ex) {
            log.error("Error while sending the file:{} for customerId:{} ,userId:{}",
                    file.getPath(), customerId, userId);
        }
    }
}

请让我知道我是做错了还是丢失了?

Please let me know what I am doing wrong or missing ?

编辑1:我附加了响应标头:

EDIT 1: I am attaching the response header I got:

{
 "date": "Sun, 01 Jan 2017 19:11:13 GMT",
 "x-content-type-options": "nosniff",
 "access-control-max-age": "3600",
 "content-disposition": "attachment;   filename=localhost-blob-abcd.pdf",
"content-length": "172962",
"x-xss-protection": "1; mode=block",
"x-application-context": "report-server:8095",
"pragma": "no-cache",
"server": "Apache-Coyote/1.1",
"x-frame-options": "DENY",
"access-control-allow-methods": "POST, PUT, GET, OPTIONS, DELETE",
"content-type": "application/pdf;charset=UTF-8",
"access-control-allow-origin": "*",
"cache-control": "no-cache, no-store, max-age=0, must-revalidate, no-cache",
"access-control-allow-headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Auth-Provider, UserId, TeamId, Lang, CustomerId",
"expires": "0"
}


推荐答案

好的,此代码对我有用:

Ok, this code works for me:

package com.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Controller
    public class DownloadController {

        @RequestMapping("/download")
        public ResponseEntity<InputStreamResource> download() throws FileNotFoundException {
            final File file = new File("file.pdf");
            return ResponseEntity.ok()
                    .contentLength(file.length())
                    .contentType(MediaType.APPLICATION_PDF)
                    .cacheControl(CacheControl.noCache())
                    .header("Content-Disposition", "attachment; filename=" + file.getName())
                    .body(new InputStreamResource(new FileInputStream(file)));
        }
    }
}

Spring没有什么特别的引导,您可以在普通的Spring MVC中使用。

There is nothing specific to Spring Boot, you can use in with plain Spring MVC.

也许是这样的Swagger问题:通过content-disposition标头下载文件会损坏文件,而不是服务器端。您是否尝试过使用其他工具测试此API调用?例如卷曲永远不要让我失望。

Maybe it is a Swagger issue like this: File download via content-disposition header corrupts file, not a server side one. Have you tried to test this API call with some other tool? For example curl never let me down.

这篇关于Spring REST / Swagger / Postman-损坏/空白文件正在下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆