数据URL(base64)、blob、File对象相互转换(完善中)

【1】File对象(文件流)base64 格式 相互转换

File对象(文件流)→ base64 格式(pass)

// 文件上传完成调用方法
ocrAfterRead(file) {
  console.log('file----打印', file)
  let base64 = ''
  var reader = new FileReader()
  reader.readAsDataURL(file.file) // 转base64
  reader.onload = e => {
    // 读取完成,数据存储在e.target.result中
    base64 = e.target.result
    console.log('base64----打印', base64)
  }
},

// 或者
fileToBase64(file) {
 return new Promise((resolve, reject) => {
    console.log('file----打印', file)
    const reader = new FileReader()
    reader.readAsDataURL(file) // 转base64
    reader.onload = e => {
      // 读取完成,数据存储在e.target.result中
      const base64 = e.target.result as string
      resolve(base64)
    }
  })
}

base64 格式 → File对象(文件流)

在JavaScript中,可以使用Base64编码的字符串创建一个Blob对象,然后通过URL.createObjectURL方法创建一个文件的URL,最终可以转换为File对象。以下是一个将Base64字符串转换为File文件流的示例代码:

function base64ToFile(base64Data, filename) {
  // 将base64的数据部分提取出来
  const parts = base64Data.split(';base64,');
  const contentType = parts[0].split(':')[1];
  const raw = window.atob(parts[1]);
  
  // 将原始数据转换为Uint8Array
  const rawLength = raw.length;
  const uInt8Array = new Uint8Array(rawLength);
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  
  // 使用Blob创建一个新的文件
  const blob = new Blob([uInt8Array], {type: contentType});
  
  // 创建File对象
  const file = new File([blob], filename, {type: contentType});
  
  return file;
}
 
// 使用示例
const base64Data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...'; // 这里应该是完整的Base64编码字符串
const filename = 'image.png'; // 文件名
const file = base64ToFile(base64Data, filename);
console.log(file);

↑↑↑↑ 这段代码首先通过Base64数据的分割,提取出数据类型和数据部分,然后使用window.atob将Base64编码的数据解码为二进制字符串,接着将这个字符串转换为Uint8Array,最后使用这个Uint8Array创建一个Blob对象,再通过这个Blob对象创建一个File对象。这样就可以得到一个File文件流对象,可以用于文件上传等操作。

// 另一种转换办法
// /*将base64转换为file对象*/
export function dataURLtoFile(dataURL, fileName, fileType) {
  const arr = dataURL.split(',')
  // const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: fileType || 'image/jpg' })
  // callback(new File([u8arr], fileName, { type: fileType || 'image/jpg' }))
}

【2】File对象(文件流)blob 格式 相互转换

File对象(文件流)→ blob 格式

fileToBlob (file)  {
    var reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function (event) {
        let blob = new Blob([event.target.result], { type: file.type });
        //{ type: file.type } 预览blob发现乱码可能是type不对  要获取file文件的type
        window.URL = window.URL || window.webkitURL;
        let blobURL = window.URL.createObjectURL(blob);
        //blobURL 就是需要的blob预览路径
        console.log(blobURL);
        window.open(blobURL)
    }
}

blob 格式 → File对象(文件流)

// 假设我们已有一个Blob对象
const blob = new Blob(["Hello, world!"], { type: "text/plain" });
 
// 转换Blob为File对象
const file = new File([blob], "example.txt", {
  type: blob.type,
});
 
// 输出File对象的一些信息
console.log(file);

【2】base64 格式blob 格式 相互转换

base64 格式→ 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 格式

// Blob转Base64
function blobToBase64(blob, callback) {
  const reader = new FileReader();
  reader.onload = function(event) {
    callback(event.target.result);
  };
  reader.readAsDataURL(blob);
}

使用示例

// 示例:使用函数
const base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...'; // 示例Base64字符串
const mimeType = 'image/png'; // Base64数据的MIME类型
 
// Base64转Blob
const blob = base64ToBlob(base64String.split(',')[1], mimeType);
 
// Blob转Base64
blobToBase64(blob, function(base64) {
  console.log(base64); // 输出转换后的Base64字符串
});
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐