js实现baseurl和blob之间相互转换的三种方式
// Base64字符串转Blob对象
function base64ToBlob(base64, mimeType) {
const byteCharacters = atob(base64);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: mimeType});
}
// Blob对象转Base64字符串
function blobToBase64(blob, callback) {
const reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result);
};
reader.readAsDataURL(blob);
}
// Blob对象转成URL
function blobToUrl(blob, mimeType) {
return URL.createObjectURL(blob);
}
// URL转Blob对象
function urlToBlob(url) {
return fetch(url).then(response => response.blob());
}
// Base64字符串转URL
function base64ToUrl(base64, mimeType) {
return 'data:' + mimeType + ';base64,' + base64;
}
// URL转Base64字符串
function urlToBase64(url) {
return fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.onerror = reject;
reader.readAsDataURL(blob);
}));
}
// 示例代码
// 假设有一个Base64字符串
const base64Str = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...';
// Base64字符串转Blob对象
const blob = base64ToBlob(base64Str.split(',')[1], base64Str.split(';')[0].split(':')[1]);
// Blob对象转成URL
const blobUrl = blobToUrl(blob);
// Blob对象转Base64字符串
blobToBase64(blob, base64 => console.log(base64));
// URL转Base64字符串
urlToBase64(blobUrl).then(base64 => console.log(base64));
// Base64字符串转URL
const base64Url = base64ToUrl(base64Str);
console.log(base64Url);
// URL转Blob对象
urlToBlob(base64Url).then(blob => console.log(blob));
这段代码提供了Base64、Blob和URL之间互相转换的函数,并给出了转换的示例代码。这些函数可以帮助开发者在处理文件上传和下载时进行格式转换。
评论已关闭