做一个文件导出,后台程序给我返回了一个文件流,之前都没这样操作过,js要怎么操作文件流?
AJAX方法
/**
* @param method 请求方式
* @param url 你的请求地址
* @param filename 文件名 // 这个根据具体需求,看你传进来还是什么方式获取
*/
function downloadFile(options) {
var xhr = new XMLHttpRequest()
xhr.open(options.method || 'POST', options.url, true)
xhr.responseType = 'blob'
xhr.send()
xhr.onload = function() {
if (this.status == 200) {
var blob = this.response
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, options.filename)
} else {
var a = document.createElement('a')
var blobUrl = window.URL.createObjectURL(blob)
a.href = blobUrl
a.download = options.filename
a.click()
window.URL.revokeObjectURL(options.url)
a = null
}
}
}
}
const reader = res.body.getReader();
const fileArr = []; // 存放
const stream = new ReadableStream({
start(controller) {
function push() {
// "done"是一个布尔型,"value"是一个Unit8Array
reader.read().then(({ done, value }) => {
if (done) { // 接受结束
console.log("ok");
const blob = new Blob(imageArr);
const file = new FileReader();
file.onload = function (e) {
self.img = e.target.result;
};
file.readAsDataURL(blob);
return;
}
fileArr.push(value); // 因为如果文件很大一次性接受不完,就需要多次接受数据,直到完成
push();
});
}
push();
}
});
10 回答11.2k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
你是 AJAX 发起的请求吗?
那就指定接收响应为
blob
,利用URL.createObjectURL
方法转为本地链接并唤起保存。