1.前端
var requestUrl = "${ctx}/wms/preEntry/fileDownload?fileName="+row.upFileName+"&forId="+row.forId;
var xhr = new XMLHttpRequest();
//GET请求,请求路径url,async(是否异步)
xhr.open('GET', requestUrl, true);
//设置响应类型为 blob
xhr.responseType = 'blob';
//关键部分
xhr.onload = function (e) {
//如果请求执行成功
if (this.status == 200) {
var blob = this.response;
var a = document.createElement('a');
blob.type = "application/octet-stream";
//创键临时url对象
var url = URL.createObjectURL(blob);
a.href = url;
a.download=row.upFileName;
a.click();
//释放之前创建的URL对象
window.URL.revokeObjectURL(url);
}
};
//发送请求
xhr.send();
2.后端
/***
* 单个文件下载
*/
@RequestMapping(value = "fileDownload", method = RequestMethod.GET)
@ResponseBody
public void fileDownload(HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
BufferedInputStream br = null;
OutputStream out = null;
try {
// 格式化拼接资源的相对路径
String filePath = url + "/" + fileName;
File file = new File(filePath);
if (!file.exists()) {
response.sendError(404, "File not found!");
return;
}
br = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
out = response.getOutputStream();
while ((len = br.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
out.flush();
out.close();
br.close();
}
}