Skip to content

@longmo-utils/browser / blobToBase64

Function: blobToBase64()

ts
function blobToBase64(blob): Promise<string>;

将 Blob 转换为 Base64 字符串

Parameters

ParameterTypeDescription
blobBlob要转换的 Blob 对象

Returns

Promise<string>

返回 Base64 编码字符串

Examples

typescript
const blob = new Blob(['hello world'], { type: 'text/plain' });
const base64 = await blobToBase64(blob);
console.log(base64); // 'aGVsbG8gd29ybGQ='
typescript
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const base64 = await blobToBase64(file);
const dataUrl = `data:${file.type};base64,${base64}`;
typescript
const blob = await fetch('https://example.com/image.png').then(r => r.blob());
const base64 = await blobToBase64(blob);
// 上传 base64 数据...

Released under the MIT License.