直奔主题!
Java代码
/**
* 下载文件
* @param path
* @param fileName
* @param response
*/
public static void downLoad(String path, String fileName,HttpServletResponse response) {
// 服务器保存的文件地址,即你要下载的文件地址(全路径)
File file = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
response.setContentType("application/octet-stream");
outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(buffer);
outputStream.flush();
}
catch (IOException e) {
e.printStackTrace();
throw new GGException(e.getMessage());
}
finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
前端代码
// 下载文件
function downLoad(sid, fileName) {
var url = "/file/downFileBySid?sid=" + sid;
var xhr = new XMLHttpRequest();
xhr.open(‘GET‘, url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status === 200) {
debugger
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function(e) {
var a = document.createElement(‘a‘);
a.download = fileName;
a.href = e.target.result;
$(‘body‘).append(a);
a.click();
}
} else {
alert("下载失败");
}
};
xhr.send();
}
最开始用
jquery
的ajax
发起请求,直接在response
中返回的是文件流,没有blob
类型返回格式。苦恼了好半天,希望大家别走弯路。
如果你用
swagger
测试请求会直接给你生成一个下载连接,它自己内部处理了,但我们只能依赖a
链接形式。附一个比较好的类似文章,供大家参考。Java下载文件
原文地址:https://www.cnblogs.com/gyyyblog/p/12675594.html
时间: 2024-11-09 03:15:08