如何解决如何将JavaScript中的数据缓冲区转换为文件?
我正在从客户端的节点/ express端点接收数据缓冲区,我想将缓冲区转换为文件。
文件可以是pdf,文本文档或图像。端点告诉我的唯一信息是它正在发送一个八位位组流。
我该怎么做?
这是我到目前为止在客户端使用的代码
const xhr = new XMLHttpRequest();
xhr.open("POST","MY_URL",true);
xhr.responseType = "arraybuffer";
// I need to send some data for the request
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
// send request
xhr.send(`identifier=${myIdentifier}`);
xhr.onload = function (xEvent)
{
const arrayBuffer = xhr.response;
if (arrayBuffer)
{
const byteArray = new Uint8Array(arrayBuffer);
const url = window.URL.createObjectURL(new Blob([byteArray]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download","file.pdf"); //or any other extension
document.body.appendChild(link);
link.click();
}
};
解决方法
将arraybuffer转换为base64,然后转换为url,为视图生成fileUrl
arrayBufferToBase64(Arraybuffer,Filetype,fileName) {
let binary = '';
const bytes = new Uint8Array(Arraybuffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
const file = window.btoa(binary);
const mimType = Filetype === 'pdf' ? 'application/pdf' : Filetype === 'xlsx' ? 'application/xlsx' :
Filetype === 'pptx' ? 'application/pptx' : Filetype === 'csv' ? 'application/csv' : Filetype === 'docx' ? 'application/docx' :
Filetype === 'jpg' ? 'application/jpg' : Filetype === 'png' ? 'application/png' : '';
const url = `data:${mimType};base64,` + file;
// url for the file
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
// download the file
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。