后端 下载功能实现
public void downloadFiles(HttpServletResponse response, String nowFileName, String rawFileName) {
try {
File file = new File(fileUrl + nowFileName);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(rawFileName, "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/force-download");
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
$(document).on("click",".auploadfilename",function(data){
let filName = this.innerText;
$.ajax({
url: "./downloadFile",
type: "post",
data: {
nowFileName: attachments.get(filName),
rawFileName: filName,
},
dataType: 'binary',
xhrFields: {responseType: 'blob'},
success: function(result, status, xhr){
const fileName = filName;
// 可通过XMLHttpRequest对象,获取响应头
console.log(xhr);
// 浏览器兼容 参数Blob类型
const downloadURL = (window.URL || window.webkitURL).createObjectURL(result);
// 创建a标签
var a = document.createElement('a');
// 下载后文件的名字
a.download = fileName;
a.href = downloadURL;
document.body.appendChild(a);
a.click();
setTimeout(function () {
// 移除内存中的临时文件路径和为下载而创建的a标签
URL.revokeObjectURL(downloadURL);
a.remove();
}, 10000);
}
});
})