我在stackoverflow上尝试了以前的解决方案以及其他选项,包括将responseType定义为" arraybuffer"和" blob",我无法下载客户端生成的xlsx文件。 repsonse.data采用byte []的形式。 我看到该文件有内容,但当我尝试打开它时,它说 - "文件格式或文件扩展名无效"
UI片段:
axios.post('/api/report/generateReport', {}, {
params: {
reportId: this.state.reportId,
lob: this.state.lob
}
}, {responseType: 'arraybuffer'})
.then(function (response) {
var blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
FileSaver.saveAs(blob, 'Metrics.xlsx');
})
后端代码段
@POST
@Path("/generateReport")
public Response generateReport(@QueryParam("reportId") int reportId, @QueryParam("lob") String lob) {
Response response = null;
byte[] contents = null;
contents = metricsReport.generateReport(lob);
response = Response.status(Response.Status.OK).entity(contents).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Content-Disposition", "attachment; filename=Metrics.xlsx").allow("OPTIONS")
.build();
return response;
}
答案 0 :(得分:1)
我认为您需要在服务器的响应中将content-type设置为application/octet-stream
。
像(春季靴子) -
return ResponseEntity.ok().contentLength(file.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header("Content-disposition", "attachment; filename=Metrics.xlsx")
.body(inputStreamResource)