【问题标题】:Unable to download xlsx from web service无法从 Web 服务下载 xlsx
【发布时间】:2017-10-31 01:15:45
【问题描述】:

我正在尝试从基于 RESTEasy 的 Web 服务下载使用 Apache XSSF 生成的 xlsx 文件。

我可以下载文件,但是当双击打开时,它说文件不能打开:

以下是源代码:

网络服务控制器:

@GET
@Path(/download)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile() {

    ByteArrayOutputStream baos = myService.processGbiValidationExceptions();

    ResponseBuilder response = Response.ok((Object) baos.toByteArray());
    response.header("Content-Disposition", "attachment;filename=My_File.xlsx");
    return response.build();
}

服务:

public ByteArrayOutputStream processGbiValidationExceptions() {
    XSSFWorkbook workbook = new XSSFWorkbook();

    // code to write to workbook


    // Create stream
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        workbook.write(baos);
    } catch (IOException e) {
        LOGGER.error("Error occurred while writing workbook to stream", e);
        throw new IptException(e);
    }

    return baos;
}

有什么线索我在这里做错了吗?谢谢

P.S.:我在 Mac 上!

【问题讨论】:

    标签: java web-services download resteasy xssf


    【解决方案1】:

    我之前用于下载文件的客户端代码几乎没有问题。现在,我正在使用download.js,它可以正常工作。

    下面是代码:

     import download from 'downloadjs';    
        .
        .
        .
        fetch(FETCH_URL, {
          method: 'GET',
          dataType: 'json',
          credentials: 'include'
        }).then(response => {
            if(response.status === 200) {
                return response.blob();
            }
          }, () => {
            // when error do something
          }
        ).then(
          // Following line helps download
          blob => download(blob, "someexcel.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        )
    

    另外,需要将 MIME 类型设置为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 才能下载 xlsx 文件:

    @Produces("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    

    干杯

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2015-04-04
      • 2015-01-19
      • 2015-03-21
      相关资源
      最近更新 更多