目录

JavaScript多种文件类型格式互转

本文介绍几个 JS 函数用于数据转换

  • Base64 转 Blob 对象
  • Base64 转 File 对象

Base64 转 Blob 对象

function base64ToBlob(base64) {
  var base64Split = base64.split(",");
  var binStr = atob(base64Split[1]),
    len = binStr.length,
    arr = new Uint8Array(len);

  for (var i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i);
  }
  return new Blob([arr], { type: base64Split[0].split(":")[1] });
}

Base64 转 File 对象

function base64ToFile(base64, filename) {
  var base64Split = base64.split(",");
  var base64Data = base64Split[1];
  var contentType = base64Split[0].split(":")[1];
  var sliceSize = 1024;
  var byteCharacters = atob(base64Data);
  var bytesLength = byteCharacters.length;
  var slicesCount = Math.ceil(bytesLength / sliceSize);
  var byteArrays = new Array(slicesCount);

  for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
    var begin = sliceIndex * sliceSize;
    var end = Math.min(begin + sliceSize, bytesLength);

    var bytes = new Array(end - begin);
    for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
      bytes[i] = byteCharacters[offset].charCodeAt(0);
    }
    byteArrays[sliceIndex] = new Uint8Array(bytes);
  }
  return new File(byteArrays, filename, { type: contentType });
}