// 将 Blob 对象转换为 Base64 字符串的示例代码
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob); // 将 Blob 转换为 Data URL 格式
reader.onloadend = function() {
if (reader.result) {
// Data URL 格式为 "data:<mime type>;base64,<data>"
// 我们只需要 <data> 部分,所以去掉前面的部分
const base64String = reader.result.replace(/^data:.+;base64,/, '');
resolve(base64String);
} else {
reject(new Error('Failed to read the Blob as Base64'));
}
};
reader.onerror = function(error) {
reject(error);
};
});
}
// 示例用法
const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
blobToBase64(blob).then(base64String => {
console.log(base64String); // 输出 Base64 编码的字符串
}).catch(error => {
console.error(error);
});
上一篇:js 字符串比较大小
下一篇:js 异步执行
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站