Я следил за this Опубликовать по функциональности: клиент может загрузить файл (то есть csv, pdf и zip) на данный момент.Весна REST/Swagger/Почтальон - Поврежденный/пустой файл, загруженный
Но либо я получаю pdf-документ, который пуст, либо при попытке с zip-файлом он поступает как поврежденный. Только CSV работает нормально.
Я проверил заголовки, все кажется стандартным. Я даже не использую «application/octet-stream» и использую «application/pdf» для pdf, «application/csv» для csv и «application/zip» для zip, чтобы избежать каких-либо проблем с клиентом. Я использую swagger 2.4 для тестирования моего apis. Вот мой код.
@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);
}
}
}
Пожалуйста, дайте мне знать, что я делаю неправильно или не хватает?
EDIT 1: Я прилагаю заголовок ответа я получил:
{
"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"
}
Спасибо за быстрый ответ. Но ответ такой же - черный PDF и поврежденный zip-файл. –
@ balboa_21 Предоставлен пример кода, который реализует буферный файл в ответную копию с помощью API ResponseEntity. –
Привет @yanys, по-прежнему та же проблема. Пустой файл pdf + zip поврежден. Только csv работает нормально. И конечно, я изменю название, я не знал, что еще поставить, поэтому я написал Spring Boot. Спасибо. Кстати, я использую чванство для тестирования. –