【问题标题】:How to download Excel using spring rest service / spring boot如何使用 spring rest 服务/spring boot 下载 Excel
【发布时间】:2020-01-02 19:39:21
【问题描述】:

使用 spring boot 下载时 Excel 下载不工作 - 问题可能是设置 CONTENT TYPE ,我怀疑! 我尝试设置不同的 CONTENT TYPE 标题,但不能使用 EXCEL。

我的要求:下面的代码应该对所有类型的文件都是通用的。

@GetMapping(value = "/files/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<ByteArrayResource> downloadAnyFile()
{

byte[] byteArray;  // data comes from external service call in byte[]

ByteArrayResource resource = new ByteArrayResource(byteArray, docName);
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, ATTACHMENT + docName)
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .contentLength(resource.contentLength())
                        .body(resource);

// Also tried this below content-type but not working
String mimeType = ServletContext.getMimeType(fileName);
 .contentType(MediaType.parseMediaType(mimeType))

}

I am seeing warning of file corrupted while opening , The downloaded excel 文件不应损坏。它应该像上传前一样打开。

【问题讨论】:

标签: java spring rest spring-boot


【解决方案1】:

请尝试以下代码。

@GetMapping(value = "/files/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  public ResponseEntity<?> downloadAnyFile() {
    String dirPath = "your-location-path";
    byte[] byteArray;  // data comes from external service call in byte[]
    try {
       String fileName = "your-custom-file-name";
      byteArray = Files.readAllBytes(Paths.get(dirPath + fileName));
    } catch (IOException e) {
      e.printStackTrace();
    }
    return ResponseEntity.ok()
        .contentType(MediaType.APPLICATION_OCTET_STREAM)
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
        .body(byteArray);
  }

您可以根据需要使用@GetMapping@PostMapping

【讨论】:

  • 我已经意识到问题是,当我上传/发送 excel 文件的文件内容时(其余文件,例如:pdf、csv、.docx .zip 没有问题)作为 byte[] byteArr = MultipartFile.getBytes() 到文件存储 REST 服务输入,数据正在损坏。我不明白为什么会这样!而且我的下载功能没有任何问题。我意识到了。
猜你喜欢
  • 2016-06-11
  • 2015-03-17
  • 1970-01-01
  • 2015-01-31
  • 2019-05-15
  • 2018-09-28
  • 2015-06-07
  • 2015-04-09
  • 2017-03-19
相关资源
最近更新 更多