无法从网络服务

时间:2017-10-31 01:15:45

标签: java web-services download resteasy xssf

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

我可以下载该文件但是当双击打开时,它说文件无法打开:

enter image description here

以下是源代码:

网络服务控制器:

@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上!

1 个答案:

答案 0 :(得分: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")

干杯