标题前言:最近导出文件喜欢用blob的形式,不占用磁盘资源
需要注意的是中文文件名称后端要提前加密,在请求头中传过来.前端再解码拿到
1.前端代码
exportMethod() {
var xhr = new XMLHttpRequest(); // 用这种原生请求下载后端返回的二进制流打开就不会出现空白
xhr.open(
"get",
"/download/excel/publicity_list?contest_id="+that.queryParams.contest_id+"&group_id="+that.queryParams.group_id,
true
);
xhr.responseType = "blob";
xhr.onload = function() {
that.loading = false;
const url = window.URL.createObjectURL(this.response);
const disposition =xhr.getResponseHeader('content-disposition');
var filename = "";
var realFileName="";
if (disposition && disposition.indexOf('inline') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
realFileName=URLDecoder.decode(filename, "utf-8");
}
}
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", realFileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
xhr.send();
},
2.后端代码
public void outputMethod(HttpServletResponse response,String filePath){
ServletOutputStream out = null;
File file = new File(filePath);
FileInputStream inputStream=null;
try{
out = response.getOutputStream();
inputStream = new FileInputStream(file);
if(filePath.contains(".xlsx")){
//
/** 导出excel文件流 */
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
response.setCharacterEncoding("UTF-8");
}else{
/** 导出pdf文件流 */
response.setCharacterEncoding("UTF-8");
response.setContentType("application/pdf");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename="+ URLEncoder.encode(file.getName(),"UTF-8"));
}
// 读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}catch (Exception e){
e.printStackTrace();
}finally{
try {
inputStream.close();
} catch (IOException e) {
logger.error("输入流关闭失败, {}", e);
}
try {
out.close();
} catch (IOException e) {
logger.error("输出流关闭失败, {}", e);
}
}
//删除.xlsx 或 pdf文件
file.delete();
}