常见的做法一般是直接通过请求接口响应对象response把文件输出
java
/**
* 导出列表
*
* @param request
* @param response
*/
@Override
public void export(AuctionRequest request, HttpServletResponse response) throws IOException {
Map<String, Object> queryMap = Maps.newHashMap(BeanConvertUtils.beanToMap(request));
List<Auction> auctions = auctionManager.listAuctions(queryMap);
if (CollectionUtils.isEmpty(auctions)) {
throw new AuctionException("当前数据为空");
}
List<AuctionDataExportModel> auctionExportModels = auctions.stream().map(item -> {
AuctionDataExportModel auctionExportModel = new AuctionDataExportModel();
auctionExportModel.setAuCode(item.getAuCode());
auctionExportModel.setAuTitle(item.getAuTitle());
return auctionExportModel;
}).collect(Collectors.toList());
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("导出", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + System.currentTimeMillis() + ".xlsx");
EasyExcel.write(response.getOutputStream(), AuctionDataExportModel.class).sheet("数据区").doWrite(auctionExportModels);
}
这样操作乍一看没啥问题.但是我这边前端同事是使用的axios发送的请求,必须指定响应类型为 'arraybuffer' 或者 'blob'.
javascript
axios({
method: 'post',
url: '/export',
responseType: 'arraybuffer',//'blob'
}).then(res => {})
正常下载是没有问题的,一旦代码报错.因为指定了响应类型.就拿不到返回的错误信息了.
于是采用了成功的时候后端直接把文件上传到s3服务器,然后把文件地址返给前端.出错的时候把错误信息返给前端,就解决了上述的问题
直接上代码
java
/**
* 导出列表
*
* @param request
*/
@Override
public String export(AuctionRequest request) {
Map<String, Object> queryMap = Maps.newHashMap(BeanConvertUtils.beanToMap(request));
List<Auction> auctions = auctionManager.listAuctions(queryMap);
if (CollectionUtils.isEmpty(auctions)) {
throw new AuctionException("当前数据为空");
}
List<AuctionDataExportModel> auctionExportModels = auctions.stream().map(item -> {
AuctionDataExportModel auctionExportModel = new AuctionDataExportModel();
auctionExportModel.setAuCode(item.getAuCode());
auctionExportModel.setAuTitle(item.getAuTitle());
return auctionExportModel;
}).collect(Collectors.toList());
//上传至s3服务器,同时将路径返回给前台
ByteArrayOutputStream bos = new ByteArrayOutputStream();
EasyExcel.write(bos, AuctionDataExportModel.class).sheet("数据区").doWrite(auctionExportModels);
byte[] binary = bos.toByteArray();
InputStream inputStream = new ByteArrayInputStream(binary);
String excelName = "导出" + IdWorker.getMillisecond() + ".xls";
String returnFilePath = CommonsConstants.STORE_AUCTION_SYNC_EXCEL + excelName;
PutObjectResult putObjectResult = s3Util.uploadFile(inputStream, "xls", returnFilePath);
org.wildfly.common.Assert.assertNotNull(putObjectResult);
return returnFilePath;
}