java实现文件导出,一般是get请求。但是有可能会有特殊情况必须用post请求方式实现。
比如我实际中遇到的情况:前端需要向后端传输图片。并在导出的文档中解析出来。只能使用post请求。
实现方法:
@ApiOperation(value = "导出评估报告", notes = "导出评估报告")@RequestMapping(value = "/exportRiskReport", method = RequestMethod.POST)public void exportRiskReport(@RequestBody ExportReportDto exportReportDto, HttpServletRequest request, HttpServletResponse response) {try {String templetKeyId = exportReportDto.getTempletKeyId();String institutionRiskKey = exportReportDto.getInstitutionRiskKey();String taskNo = exportReportDto.getTaskNo();List<Map<String,Object>> imgList = exportReportDto.getMapActions();inherentRiskAssessMentService.exportRiskReport(templetKeyId, institutionRiskKey, taskNo,imgList, request, response);} catch (Exception e) {logger.error("Exception{}", e);e.printStackTrace();}return;}
实际导出的方法,根据正常需要编写即可。
前端:
/*** 创建blob对象,并利用浏览器打开url进行下载* @param data 文件流数据*/downloadFile(data) {// 下载类型 xlsconst contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';// 下载类型:csvconst contentType2 = 'text/csv';const blob = new Blob([data], { type: contentType });const url = window.URL.createObjectURL(blob);// 打开新窗口方式进行下载// window.open(url);// 以动态创建a标签进行下载const a = document.createElement('a');const fileName = this.datePipe.transform(new Date(), 'yyyyMMdd');a.href = url;// a.download = fileName;a.download = fileName + '.xlsx';a.click();window.URL.revokeObjectURL(url);}
