我曾尝试使用restController生成文件字节数组,但当我将其返回给react时,react没有得到字节数组。前端使用react,后端使用spring restController,我使用Http进行前台和后台通信。我的代码中有什么错误吗?谢谢你的帮助。
restController:
String fileName = DateUtility.dateToStr(new Date(), DateUtility.YYYYMMDD_HHMMSS) + " - "
+ reportNmaeByType.get(exportParam.getReportType()) + ".xls";
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(excelByte, HttpStatus.OK);
react:
createExcelFile(){
var params = {
reportResultList: this.state.reportResult,
reportType: getReportSelector().state.selectedReportType,
selectColumnMap: this.state.selectColumn,
selectCusColumnMap: this.state.selectCusColumn
}
fetch("http://localhost:8080/mark-web/file/createExcel", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
}).then(res => {
if (res.ok) {
console.log(res)
console.log(this)
console.log('create excel success!!')
} else {
console.log('create excel Fail!!')
}
})
}
返回:enter image description here
更新2018/09/16:
我在react函数中添加了一些代码,它终于可以下载excel文件,但文件被破坏了。我已经检查了blob对象作为响应。它显示blob是json对象。是不是因为我没有解码成blob对象?
React:
}).then(res => {
if(!res.ok){
console.log("Failed To Download File")
}else{
return res.blob()
}
}).then(blob => {
console.log(blob)
let url = URL.createObjectURL(blob)
console.log(url)
var downloadAnchorNode = document.createElement('a')
downloadAnchorNode.setAttribute("href", url)
downloadAnchorNode.setAttribute("download", "excel" + ".xls")
downloadAnchorNode.click()
downloadAnchorNode.remove()
})
响应:
发布于 2018-09-10 20:39:00
因此,从您的网络图看,您的请求似乎正在按预期完成,但您只是无法从响应中派生出ByteArray。
使用返回.x的JSON或XML的普通请求。你可以一口气读完它们,因为它们是身体的一部分。然而,在您的示例中,您的主体包含一个Stream
。因此,您将不得不自己处理读取该流的问题。
你可以用response.blob()
做到这一点:
blob()方法读取流完成并返回一个Blob对象。然后,您可以使用此blob对象嵌入图像或download the file。出于所有的意图和目的,我建议使用这个。除非您正在处理大文件(>500MB),否则它应该可以满足您的需求。
例如:
fetch("http://localhost:8080/mark-web/file/createExcel", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
}).then(res => {
if (!res.ok) {
throw new Error(res.statusText);
} else {
return res.blob()
}
}).then(blob => {// do your thing})
.catch(err => console.log(error))
或
您可以使用实验性的ReadableStream界面来更精细地控制您想要对其执行的操作。
https://stackoverflow.com/questions/52253197
复制相似问题