二進(jìn)制流格式
blob格式
跟用input上傳文件的獲取到的差不多
用URL.createObjectURL(blob)轉(zhuǎn)化后是這樣文章來源:http://www.zghlxwxcb.cn/news/detail-686931.html
base64格式
文章來源地址http://www.zghlxwxcb.cn/news/detail-686931.html
二進(jìn)制流轉(zhuǎn)blob
getFiles(res, type, filename) {
// 創(chuàng)建blob對象,解析流數(shù)據(jù)
const blob = new Blob([res], {
// 如何后端沒返回下載文件類型,則需要手動設(shè)置:type: 'application/pdf;chartset=UTF-8' 表示下載文檔為pdf,如果是word則設(shè)置為 msword,excel為excel
type: type
});
const a = document.createElement("a");
// 兼容webkix瀏覽器,處理webkit瀏覽器中href自動添加blob前綴,默認(rèn)在瀏覽器打開而不是下載
const URL = window.URL || window.webkitURL;
// 根據(jù)解析后的blob對象創(chuàng)建URL 對象
const herf = URL.createObjectURL(blob);
this.pdfUrl = herf;
},
this.getFiles((res, "application/pdf;chartset=UTF-8");
blob轉(zhuǎn)base64
blobToBase64(blob, callback) {
const fileReader = new FileReader();
fileReader.onload = (e) => {
callback(e.target.result);
};
fileReader.readAsDataURL(blob);
},
this.blobToBase64(blob, (dataurl) => {
this.pdfBase64 = dataurl;
console.log("base64", this.pdfBase64);
});
base64轉(zhuǎn)blob
base64ToBlob(code) {
//Base64一行不能超過76字符,超過則添加回車換行符。因此需要把base64字段中的換行符,回車符給去掉,有時候因?yàn)榇嬖谛枰鸭犹柨崭裰惖膿Q回來,取決于base64存取時的規(guī)則。
code = code.replace(/[\n\r]/g, "");
var raw = window.atob(code);
let rawLength = raw.length;
//轉(zhuǎn)換成pdf.js能直接解析的Uint8Array類型
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
console.log(uInt8Array, "uInt8ArrayuInt8Array");
console.log(new Blob([uInt8Array], { type: "application/pdf" }));
return new Blob([uInt8Array], { type: "application/pdf" }); //轉(zhuǎn)成pdf類型
},
二進(jìn)制流轉(zhuǎn)base64
getBase64(data) {
const blob = new Blob([data], { type: "image/jpg" }); //類型一定要寫?。。?/span>
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
})
},
到了這里,關(guān)于文件流互相轉(zhuǎn)換(blob轉(zhuǎn)base64,二進(jìn)制流)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!