Buffer -> ArrayBuffer
const arraybuffer = new Int8Array(buffer.data);
ArrayBuffer -> Blob
const blob = new Blob([arraybuffer], { type : 'application/pdf'});
项目案例:前端通过 ajax(responseType = 'blob')获取文件数据进行下载。代码如下,downloadFromS3 是共通方法通过 AWS S3 获取文件,因为返回的是 nodejs 的 Buffer 类型。前端 ajax 会自动转换为 blob 类型,所以没有问题。
但是现在后端可能会报 error ,想让前端截获 error ,这时前端会将 error 信息转换成 blob。如果读取 blob 信息也可以获取 error 信息,但是有没有其它方法,比如 responseType = 'json' 就可以正常读到 error 信息,但是前端怎么将 buffer 转换为 blob 呢?
后端 express.js
app.get('/', async (req, res) => {
const pdf = await downloadFromS3("pdf/胡雨南的简历.pdf");
res.send(pdf);
})
前端 index.js
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
const url = URL.createObjectURL(xhttp.response);
const aTag = document.createElement('a');
aTag.setAttribute('download', 'test');
aTag.href = url;
aTag.click();
};
xhttp.onerror = function() {
console.log(xhttp.response);
};
xhttp.open('GET', 'http://localhost:3000', true);
xhttp.responseType = 'blob';
xhttp.send();
方法:
更改后端 express.js
app.get('/', async (req, res) => {
const pdf = await downloadFromS3("pdf/胡雨南的简历.pdf");
res.send({pdf : pdf});
})
更改前端 index.js
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
const buffer = xhttp.response.pdf;
const dataView = new Uint8Array(buffer.data);
const blob = new Blob([dataView], { type : 'application/pdf'});
const url = URL.createObjectURL(blob);
const aTag = document.createElement('a');
aTag.setAttribute('download', 'test');
aTag.href = url;
aTag.click();
};
xhttp.onerror = function() {
console.log(xhttp.response);
};
xhttp.open('GET', 'http://localhost:3000', true);
xhttp.responseType = 'blob';
xhttp.send();