首先是JAVA后台代码,资源请求都用GET比较好,但是要注意前端传路径回来的长度是否超过GET请求限制长度
/**
*
* @param response
* @param pathUrl
*/
@GetMapping(value = "/common/download/resourceStream")
public void resourceStreamDownload(HttpServletResponse response,
@RequestParam(value = "pathUrl",required = false) String pathUrl){
//这三行代码是我去其他地方获得的流文件
Response pathUrlResponse = dfsFeignClient.downloadFileByPath(pathUrl);
Response.Body body = pathUrlResponse.body();
InputStream inputStream = null;
try {
//File file = new File("d:/20190906163248.png");
// 以流的形式下载文件。
//InputStream inputStream = new BufferedInputStream(new FileInputStream("d:/20190906163248.png"));
inputStream = body.asInputStream();//文件流
BufferedInputStream bins = new BufferedInputStream(inputStream);//放到缓冲流里面
byte[] buffer = new byte[inputStream.available()];
// 清空response
response.reset();
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename="+pathUrl.substring(pathUrl.lastIndexOf("/")+1,
pathUrl.length()));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
// 采用多次read的方式,这种toClient.write(buffer);方式会导致图片不完整
int length = -1;
while((length = bins.read(buffer)) != -1) {
toClient.write(buffer, 0, length);
}
bins.close();
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
接下来是前端代码,最好都使用a标签链接后台请求下载,用ajax的话会出现乱码问题暂时还没找到解决方案。
{
field : 'reserve',
title : '点击下载注册证书',
formatter:function(value){
return "<a href=/common/download/resourceStream?pathUrl="+value+">点击下载证书</a>";
}
},