2017-01-01 8 views
1

Я следил за 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" 
} 

ответ

2

Ok, этот код работает для меня:

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))); 
     } 
    } 
} 

Там нет ничего конкретного Спринг загрузки, вы можете использовать в с простой пружиной MVC.

Возможно, это проблема с Swagger: File download via content-disposition header corrupts file, а не на стороне сервера. Вы пытались протестировать этот вызов API с помощью другого инструмента? Например, curl никогда меня не подводил.

+0

Спасибо за быстрый ответ. Но ответ такой же - черный PDF и поврежденный zip-файл. –

+0

@ balboa_21 Предоставлен пример кода, который реализует буферный файл в ответную копию с помощью API ResponseEntity. –

+0

Привет @yanys, по-прежнему та же проблема. Пустой файл pdf + zip поврежден. Только csv работает нормально. И конечно, я изменю название, я не знал, что еще поставить, поэтому я написал Spring Boot. Спасибо. Кстати, я использую чванство для тестирования. –

 Смежные вопросы

  • Нет связанных вопросов^_^