1、feign接口定义(注意:Response 导包)
import feign.Response;
/**
* 导出定义
*/
@PostMapping(value="/xx/export")
Response export(@RequestBody JSONObject data);
2、接收feign的流,写入response中
/**
* 导出
*/
@PostMapping("export")
public void export(HttpServletRequest request, HttpServletResponse response) {
//调feign获取feignResponse
Response feignResponse = xxxFeign.export(param);
try {
InputStream inputStream = feignResponse.body().asInputStream();
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("导出_" + System.currentTimeMillis() + ".zip", "UTF-8"));
response.setContentType("application/octet-stream;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
os = response.getOutputStream();
byte[] b = toByteArray(inputStream);
//测试代码
writeToLocal("D:\\partner-resource\\导出_"+System.currentTimeMillis()+".zip",b);
os.write(b);
os.flush();
} catch (Exception e) {
e.printStackTrace();
response.setContentType("application/text;charset=UTF-8");
this.writeResponse(response, this.convertException(e));
}finally {
try {
os.close();
} catch (Exception e) {
}
}
}
/**
* InputStream 转换成byte[]
* @param input
* @return
* @throws IOException
*/
private static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/**
* 将bytes写入本地文件(测试代码)
* @param destination
* @param bytes
* @throws IOException
*/
private static void writeToLocal(String destination, byte[] bytes)
throws IOException {
FileOutputStream downloadFile = new FileOutputStream(destination);
downloadFile.write(bytes);
downloadFile.flush();
downloadFile.close();
}
java将InputStream或bytes写入本地文件(传送门)