网站开发中如何设计验证码,wordpress主题插件免费,自助建站最好的平台,wordpress淘宝客模板下载导出excel文件是开发中常见的需求
常见的做法一般是直接通过请求接口响应对象HttpServletResponse把文件输出
我们可以使用原生的poi工具类操作.也可以使用easypoi.easyexcel等基于poi二次封装的工具处理
下面是代码 /*** 导出列表** param request* param response*/Overri…导出excel文件是开发中常见的需求
常见的做法一般是直接通过请求接口响应对象HttpServletResponse把文件输出
我们可以使用原生的poi工具类操作.也可以使用easypoi.easyexcel等基于poi二次封装的工具处理
下面是代码 /*** 导出列表** param request* param response*/Overridepublic void export(AuctionRequest request, HttpServletResponse response) throws IOException {MapString, Object queryMap Maps.newHashMap(BeanConvertUtils.beanToMap(request));ListAuction auctions auctionManager.listAuctions(queryMap);if (CollectionUtils.isEmpty(auctions)) {throw new AuctionException(当前数据为空);}ListAuctionDataExportModel 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’.
axios({method: post,url: /export,responseType: arraybuffer,//blob
}).then(res {})正常下载是没有问题的,一旦代码报错.因为指定了响应类型.就拿不到返回的错误信息了.
于是采用了成功的时候后端直接把文件上传到s3服务器,然后把文件地址返给前端.出错的时候把错误信息返给前端,就解决了上述的问题
上代码
/*** 导出列表** param request*/Overridepublic String export(AuctionRequest request) {MapString, Object queryMap Maps.newHashMap(BeanConvertUtils.beanToMap(request));ListAuction auctions auctionManager.listAuctions(queryMap);if (CollectionUtils.isEmpty(auctions)) {throw new AuctionException(当前数据为空);}ListAuctionDataExportModel 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;}我这里是传到s3服务器,其他的文件服务器(minio.七牛云)也都提供类似的上传api.按需替换就好了.