问题描述:直接调用policy服务的导出接口可以正常导出。admin服务调用policy服务导出接口文件无法导出。
!!!!结论:policy服务导出后不能提前关闭流,feign调用后需要将响应体转换
解决方案:
-admin接口以及响应体转换方法。因为使用了feign,导致响应体结构变化,需要从里面拿到输入输出流
@ApiOperation("计划定制-导入计划")
@PostMapping("/importPlan")
public void importPlan(@RequestPart("file") MultipartFile file, HttpServletResponse response) {
try {
Response resp = marketingFeign.importPlan(file);
response.setContentType(resp.headers().get("content-type").toString());
if(!resp.headers().get("content-type").toString().contains("application/json")){
feignResp2ServletResp(resp,response);
}
} catch (IOException e) {
log.info("导入计划异常",e);
}
}
//将feignResponse转为HttpServletResponse
public void feignResp2ServletResp(Response feignResponse, HttpServletResponse response) throws IOException {
Response.Body body = feignResponse.body();
try (InputStream inputStream = body.asInputStream(); OutputStream outputStream = response.getOutputStream())
{
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, feignResponse.headers().get(HttpHeaders.CONTENT_DISPOSITION).stream().findFirst().get());
response.setContentType(feignResponse.headers().get(HttpHeaders.CONTENT_TYPE).stream().findFirst().get());
IOUtils.copy(inputStream, outputStream);
}
}
- feign方法:注意 如果是多个请求参数,也需要在前面加上@RequestPart,否则编译不通过
- ` @PostMapping(value = "/planconfig/importPlan",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Response importPlan(@RequestPart("file") MultipartFile file);`
- 导出:重点!!!创建excelWriter时需要指定).autoCloseStream(false)属性,使其写入完成后不关闭。
- 多sheet页填充
- ` try (OutputStream out = response.getOutputStream()){
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("计划导入失败结果", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
ExcelWriter excelWriter = EasyExcel.write(out).autoCloseStream(false).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0, "计划信息").head(LdContPlanDto.class).build();
excelWriter.write(planDtoList, writeSheet);
WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "责任信息").head(LdContPlanDetailDto.class).build();
excelWriter.write(detailDtoList, writeSheet1);
excelWriter.finish();
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = MapUtils.newHashMap();
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSONObject.toJSONString(map));
}`
单sheet页
EasyExcel.write(response.getOutputStream(), LcContTemplateDto.class).autoCloseStream(false).sheet("个单导入结果")
.doWrite(errorList);