Ajax 下载文件
第一篇博文,记录ajax下载二进制文件的方法
laravel 返回响应
response($file)->header('Content-Type','application/octet-stream');
前端 ajax请求
function loadeImg( name) {
const url = ‘http://localhost/xxx’;
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true); // 定义请求方式
xhr.setRequestHeader('X-CSRF-TOKEN',$('meta[name="csrf-token"]').attr('content')); // 添加 csrf 令牌
xhr.responseType = "blob"; // 返回类型blob
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {
// 请求完成
if (this.status === 200) {
// 返回200
const blob = this.response;
const reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a标签href
reader.onload = function (e) {
// 转换完成,创建一个a标签用于下载
const a = document.createElement('a');
a.download = name + '.png';
a.href = e.target.result;
$("body").append(a); // 修复firefox中无法触发click
a.click();
$(a).remove();
}
}
};
// 发送ajax请求
xhr.send()
}
简单记下
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: