- 说一下ajax请求下Excel文件踩的坑
- 当接口返回的是文件时, ajax解析给我们的是一个二进制流,ajax识别解析不了这个类型的数据,会直接把它打开展示, 然后就会出现下面这种情况.
然后我在就各种百度, 主要就是因为ajax只支持解析Json和XML格式的数据; 最后的解决办法 就是在前端用一个二进制对象接收包裹这个返回的二进制流
Blob
Blob(binary large object),二进制类文件大对象,是一个可以存储二进制文件的“容器”,HTML5中的Blob对象除了存放二进制数据外还可以设置这个数据的MIME类型。File接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
new Blob([data], {type: “application/octet-binary”})
Blob构造函数接受两个参数,第一个参数是一个包含实际数据的数组,第二个参数是数据的MIME类型。
Blob.size
blob对象的数据大小
Blob.type
表示blob对象所包含数据的MIME类型。如果实例化时未指明类型,则该值为空字符串。
后端代码
@GetMapping(value = "/export")
public void excelExport(HttpServletResponse response) {
try {
OutputStream out = response.getOutputStream();
String fileName = "item表格";
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);
Sheet sheet = new Sheet(1, 0);
List<List<String>> data = new ArrayList<>();
for (int i = 0; i < 100; i++) {
List<String> item = new ArrayList<>();
item.add("item0" + i);
item.add("item1" + i);
item.add("item2" + i);
data.add(item);
}
sheet.setAutoWidth(true);
writer.write0(data, sheet);
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
//xlsx文件标记
response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
writer.finish();
out.close();
}catch (Exception e){
log.error("==========",e);
}
}
ajax 请求方式
this.$axios({
method:'get',
url:this.$store.getters.get_url_index+'api/excel/export',
headers:{"Authorization":window.localStorage.token,"Content-Type":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
params:data,
responseType:'blob '
}).then(function(res) {
let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "表格.xlsx";
link.click();
link.remove();
}).catch(function(res){
console.log(res);
});