Article directory
1. Convert base64 string to blob object:
function convertBase64ToBlob(base64Str) {
// 将base64字符串转为二进制数据
const byteCharacters = atob(base64Str);
// 创建Blob对象
const blob = new Blob([byteCharacters], {
type: 'application/octet-stream' });
return blob;
}
2. Convert blob object to file object:
function convertBlobToFile(blob, fileName) {
// 创建File对象
const file = new File([blob], fileName, {
type: blob.type });
return file;
}
Note:
convertBase64ToBlob
The method converts the base64 string into a blob object, uses the atob method to convert the base64 string into binary data, and then uses the Blob constructor to create a Blob object and specify the file typeapplication/octet-stream
.convertBlobToFile
The method converts the blob object into a file object and uses the File constructor to create the File object.
3. Use cases:
The sample code demonstrates an example of converting a base64 image string into a file object:
const base64Str = 'data:image/png;base64,iVBORw0KG...'; // 用实际的base64字符串替换
const fileName = 'image.png';
const blob = convertBase64ToBlob(base64Str);
const file = convertBlobToFile(blob, fileName);
console.log(file);
Output result:
File(85) {
name: "image.png", lastModified: 1632490063760, lastModifiedDate: Tue Sep 24 2021 16:07:43 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 85, …}