实现下载文件功能
记录常用到的功能
服务端
public static void download(String filePath, HttpServletResponse response) throws UnsupportedEncodingException {
// 获取文件
File file = new File(filePath);
String fileName = file.getName(); //下载的文件名
// 如果文件存在,则进行下载
if (file.exists()) {
// 配置响应头
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
// 对文件名进行一次转码,下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
//第一行
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
//下一行
i = bis.read(buffer);
}
System.out.println("Download successfully!");
}
catch (Exception e) {
System.out.println("Download failed!");
}
finally {
//关闭所有流
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
前端
//根据服务断返回的响应流构建下载url
let url = window.URL.createObjectURL(new Blob([resp.data]));
//创建a标签
let a = document.createElement('a');
//隐藏a标签
a.style.display = 'none';
a.href = url;
a.setAttribute('download','filename.xlsx');
//document树中插入a标签
document.body.appendChild(a);
a.click();
//释放Blob
window.URL.revokeObjectURL(url);