Link to the original text
1. Convert the base64 file to a blob object:
function convertBase64UrlToBlob(urlData){
var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
2. Convert the blob object to base64:
function blobToDataURL(blob, callback) {
var a = new FileReader();
a.onload = function (e) { callback(e.target.result); }
a.readAsDataURL(blob);
}
3. Convert base64 to file object:
function dataURLtoFile(dataurl, filename) { //将base64转换为文件
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
4. Convert file to base64
function getBase64(file: Blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
}
4. Base64 file download
function (data) {
var fileName = data.fileName;
// 判断空
if (util.isEmpty(fileName)) return;
var bin = atob(data.base64.replace(/\s/g, ''));
var buffer = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) {
buffer[i] = bin.charCodeAt(i);
}
var blob = new Blob([buffer.buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// 输出文件
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.target = '_blank';
a.download = fileName;
a.click();
URL.revokeObjectURL(a.href);
}
};
————————————————
Copyright statement: This article is an original article of CSDN blogger "ChoneyLove", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprinting .
Original link: https://blog.csdn.net/weixin_43109722/article/details/107808130