The difference, conversion and usage scenarios of base64, blob, file and other formats of pictures

1. Difference

Base64: Base64 is a text encoding used to represent binary data. It converts binary data into a string consisting of uppercase and lowercase letters, numbers, and special characters. This is convenient for use in occasions that do not support binary data transmission or storage, such as JSON, HTML, etc.

Blob: It is an object representing a large amount of binary data, usually used to process pictures, audio, video and other files. The Blob object in the browser can generate a temporary URL for reference by other APIs through the URL.createObjectURL method.

File: The File object inherits from the Blob object and is used to represent the file selected by the user or obtained from the network. It contains metadata such as the name, type, and modification time of the file, and can be passed as parameters to other Web APIs for processing.

2. Mutual conversion

(1) Convert base64 to blob object:

function base64ToBlob(data) {
    
    
    var arr = data.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
 
    while (n--) {
    
    
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
    
     type: mime });
}

(2) Convert base64 to file object:

// 将base64转换为文件,dataurl为base64字符串,filename为文件名(必须带后缀名,如.jpg,.png)
export function dataURLtoFile (dataurl, filename) {
    
    
  const arr = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/u)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    
    
    u8arr[n] = bstr.charCodeAt(n)
  }
  const blob = new Blob([u8arr], {
    
     type: mime })
  return new File([blob], filename, {
    
     type: mime, lastModified: new Date() })
}

(3) Convert blob to base64

function blobToBase64(blob, callback) {
    
    
  var reader = new FileReader();
  reader.onload = function() {
    
    
    var dataUrl = reader.result;
    var base64 = dataUrl.split(',')[1];
    callback(base64);
  };
  reader.readAsDataURL(blob);
}

(4) blob to file

function blobToFile(blob, fileName){
    
    
   var b = blob;
   b.lastModifiedDate = new Date();
   b.name = fileName;
   return new File([b], fileName); // 使用File构造函数创建一个新文件对象
}

(5) file converted to base64

fileToBase64 = (file) => {
    
    
  const fileReader = new FileReader();
  fileReader.readAsDataURL(file);
  fileReader.onload = function () {
    
    
    return reader.result;
  };
};

Guess you like

Origin blog.csdn.net/weixin_52797317/article/details/131082263