需求:前端展示请求数据后的图片或文档等;
刚一看觉得没啥不同,还是请求数据,在success的成功函数里拿到data,然后拿到图片的路径,然后直接放到我们前端页面的图片容器里:
success:function(data){
$('.imgBox').attr('id':data.src);
}
运行发现是不行,因为以上是适用于后台返回的是个图片路径,当返回的是二进制流文件时我们要对success返回的数据文件进行处理才行;
方法一:
function downArchival(filePath,fileName) {
let url = Common.getWeSafeApiUrl() + 'File/DownLoadFile?FileName='+filePath+'&inline='+0;
let xhr = $.ajaxSettings.xhr(); //拿到原生的xhr对象
xhr.open('GET', url, true); //发送请求获得文件
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.responseType = "blob"; //设置相应类型为blob流
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
var blob = xhr.response;
if (blob == undefined) {
this.alertService.showAlert('error', "错误", "服务器错误,请与管理员联系!");
}
else if (window.navigator.userAgent.indexOf("Chrome") !== -1) {
// Chrome version
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob) +'.pdf';
//URL.createObjectURL()会创建一个 domstring,蚕食是给出的对象的URL,这个新的URL对象表示指定的File,Blob对象;
link.download = fileName;
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(link.href); //用完之后使用URL.revokeObjectURL()释放;
}
else if (typeof window.navigator.msSaveBlob !== 'undefined') {
console.log(window.navigator.userAgent);
// IE version
window.navigator.msSaveBlob(blob, fileName);
}
else {
// Firefox version
var file = new File([blob], fileName, { type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
}
};
xhr.send();
}
方式二:
function download() {
var url = 'download/?filename=aaa.txt';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // 也可以使用POST方式,根据接口
xhr.responseType = "blob"; // 返回类型blob
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {
// 请求完成
if (this.status === 200) {
// 返回200
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
reader.onload = function (e) {
// 转换完成,创建一个a标签用于下载
var a = document.createElement('a');
a.download = 'data.xlsx';
a.href = e.target.result;
$("body").append(a); // 修复firefox中无法触发click
a.click();
$(a).remove();
}
}
};
// 发送ajax请求
xhr.send()
}
本文介绍了如何在前端处理后端返回的二进制流文件,特别是针对图片和文档等类型的数据。当后端不再返回图片路径而是二进制流时,需要在success回调中对数据进行特殊处理。文章提到了两种处理方法。
2540

被折叠的 条评论
为什么被折叠?



