反应无法获得restController响应

时间:2018-09-10 07:44:43

标签: spring reactjs rest

我尝试使用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);

反应:

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对象吗?

反应:

}).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()
    })

响应:

enter image description here

1 个答案:

答案 0 :(得分:0)

因此,从您的网络图看来,您的请求似乎已按预期完成,但是您无法从响应中导出ByteArray。

使用正常请求返回e.x的JSON或XML。您可以一口气阅读它们,因为它们是身体的一部分。但是,根据您的情况,您的身体中包含Stream。因此,您将不得不自行处理该流。

您可以使用response.blob()来实现:

blob()方法读取流以完成操作并返回一个Blob对象。然后,您可以使用此Blob对象嵌入图像或download the file。出于所有目的和目的,我建议您使用它。除非您要处理大文件(> 500 MB),否则它足以满足您的需求。

例如:

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界面来更精细地控制您要使用的界面。