在春季休息时对下载文件做出反应

时间:2018-09-07 09:28:23

标签: spring reactjs restful-url

我是React和Spring Restful的初学者。我试图编写一个spring restful下载文件功能来做出反应。我尝试使用Google搜索一些信息,但是它们对我的功能无效。

我已经看到很多页面谈到我需要使用ByteArrayOutputStream,但是我该如何从静态控制器返回响应。任何人都可以帮助我或给我一些建议。非常感谢。

反应功能:

 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!!')
        }
    })
}

Spring Restful Function:

@Override
public byte[] createExcelByReport(ReportExportParam exportParam) throws Exception {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try (HSSFWorkbook workBook = new HSSFWorkbook()) {

        HSSFSheet sheet = workBook.createSheet("result");

        // header
        List<String> headerList = Arrays.asList("date", "result", "result2");

        // create cell by header count
        HSSFRow headerRow = sheet.createRow(0);
        HSSFCell headerCell;
        for (String header : headerList) {
            headerCell = headerRow.createCell(headerList.indexOf(header));
            headerCell.setCellValue(header);
        }

        // create cell value
        HSSFRow dataRow;
        for (ReportAnalysisRo data : exportParam.getReportResultList()) {

            dataRow = sheet.createRow(exportParam.getReportResultList().indexOf(data) + 1);
            dataRow.createCell(0).setCellValue(data.getAdDateStr());
            dataRow.createCell(1).setCellValue(data.getCampaignName());
            dataRow.createCell(2).setCellValue(data.getGroupName());

        }

        workBook.write(bos);
        bos.flush();
        bos.close();
        System.out.println("Create Excel Success");

    } catch (Exception e) {
        System.out.println("Create Excel Failed");
        LOG.error(e.getMessage());
        throw e;

    }

    return bos.toByteArray();
}

0 个答案:

没有答案