在微服务项目中,我经常会碰到从一个微服务项目转发下载请求并实现下载文件的需求,因此在此做一个转发下载的示例。总的下载转发流程如下,我会按照这个流程一一介绍下载流程。
1、客户端的下载请求
这里主要介绍controller层是如何接收客户端发送请求的代码,接收参数的代码如下
@GetMapping(value = "downloadFile")
public void downloadFile( HttpServletResponse response) {
}
2、转发服务器的下载请求
转发服务器的下载请求主要通过Feign接口实现,具体实现代码如下:
Feign接口:
@PostMapping(value = "/downloadFile")
Response downloadFile();
Feign接口实现类:
@Override
public Response downloadFile() {
return null;
}
之后便可以利用Feign实现转发了controller层代码完善如下:
@GetMapping(value = "downloadFile")
public void downloadFile( HttpServletResponse response) {
InputStream inputStream = null;
try {
Response serviceResponse = queryBranchService.downloadFile(url,sapNo);
} catch (IOException e) {
e.printStackTrace();
}
}
3、最终服务器的下载请求响应
该代码的总体思路就是将文件变成输出流并写在响应中,并返回给转发服务器。
@GetMapping(value = "downloadFile")
public void downloadFile(HttpServletResponse response) {
//获取upload文件夹的路径
try {
InputStream contentInput = OkHttpClientUtils.getImage(url, null);
BufferedInputStream bufferedInputStream = new BufferedInputStream(contentInput);
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(sapNo+".png", "UTF-8"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
int length = 0;
byte[] temp = new byte[1024 * 10];
while ((length = bufferedInputStream.read(temp)) != -1) {
bufferedOutputStream.write(temp, 0, length);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
bufferedInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
4、转发服务器的下载请求响应
对转发服务器的controller层再继续完善,完善的总思路拿到中转服务器的响应,并拿出响应中输入流再变成输出流回写给客户端
@GetMapping(value = "downloadFile")
public void downloadFile( HttpServletResponse response) {
InputStream inputStream = null;
try {
InputStream inputStream = null;
try {
Response serviceResponse = queryBranchService.downloadFile();
Response.Body body = serviceResponse.body();
inputStream = body.asInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
response.setHeader("Content-Disposition", serviceResponse.headers().get("Content-Disposition").toString().replace("[", "").replace("]", ""));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
int length = 0;
byte[] temp = new byte[1024 * 10];
while ((length = bufferedInputStream.read(temp)) != -1) {
bufferedOutputStream.write(temp, 0, length);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
bufferedInputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}