Introduction and mutual conversion of base64, File, Blob, ArrayBuffer several file formats

relation

insert image description here

introduce

Blob

insert image description here

  1. introduce

    1. is an immutable, raw data file-like object
    2. is essentially an object of js
      1. size: the size of the contained data (bytes)
      2. MIMEtype: the type of data contained
    3. It stores binary data
    4. FileReaderThe contents of the blob can be read using
  2. create

    // 语法
    const blob = new Blob(array, options);
    
    // 示例
    const blob = new Blob([JSON.stringify(debug, null, 2)],   {
          
          type : 'application/json'});
    const myBlob = new Blob([1,2,3],{
          
          type:'text/plain'});
    console.log(myBlob);//Blob {size: 3, type: "text/plain"}
    console.log(myBlob.size);//3
    console.log(myBlob.type);//'text/plain'
    
    

File

insert image description here

  1. introduce

    1. Fileobject is specialBlob
    2. Instantiation has 3 parameters:new File(array, name, options)
    3. Generally, the File object is obtained by uploading
      1. By input type=fileselecting the file, return fileListthe object
      2. Drag and drop files to generate DataTransferobjects
  2. create

    const file = new File([file], file.name, {
          
          type: file.type});
    
    // input上传
    <input type="file" id="file">
    <script>
        let obj = document.querySelector('#file')
        obj.addEventListener('change', (event) => {
          
          
            console.log(event.target.files[0]);
        })
    </script>
    
    // 拖拽
    <div class="drop" style="background-color: pink; height: 50px;"></div>
    <script>
        let obj = document.querySelector('.drop')
        obj.ondragover = e => {
          
          e.preventDefault()}
        obj.ondrop = e => {
          
          
            e.preventDefault()
            console.log(e.dataTransfer.files);
        }
    </script>
    

FileReader

It is a built-in method of js, which helps to realize File/Blobthe content of the object read

readAsArrayBuffer(file) 异步按字节读取文件内容,完成之后,result属性中保存被读文件的ArrayBuffer数据对象。
readAsBinaryString(file): 异步按字节读取文件内容,结果为文件的二进制串
readAsDataURL(file) 异步读取文件内容,结果用data:url的字符串形式表示。
readAsText(file) 异步按字符读取文件内容,result中包含的是字符串。
onabort 当读取操作被中止时调用
onerror 当读取操作发生错误时调用
onload 当读取操作成功完成时调用
onloadend 当读取操作完成时调用,不管是成功还是失败
onloadstart 当读取操作将要开始之前调用
onprogress 在读取数据过程中周期性调用

binary array

  1. ArrayBuffer对象, TypedArray视图and DataView视图is an interface for JavaScript to manipulate binary data
  2. They are all 以数组的语法处理二进制数据, so collectively referred to as binary arrays
  3. Binary arrays are not really arrays, but类似数组的对象

It consists of three types of objects

  1. ArrayBuffer对象

    Represents a piece of binary data in memory, which can be manipulated through "view". The "view" implements the array interface, which means that the memory can be manipulated with the methods of the array.

  2. TypedArray视图

    Including 9 types of views, such as Uint8Array (unsigned 8-bit integer) array view, Int16Array (16-bit integer) array view, Float32Array (32-bit floating point number) array view and so on.

  3. DataView视图

    You can customize the composite format view, for example, the first byte is Uint8 (unsigned 8-bit integer), the second and third bytes are Int16 (16-bit integer), and the fourth byte is Float32 (32-bit integer) Floating-point numbers), etc., and you can also customize the endianness.

ArrayBuffer object

ArrayBuffer cannot directly read the stored content, it needs to use TypedArrayobjects or DataViewobjects to read and write

URL.createObjectURL

  1. A URL pointing to the parameter object will be created based on the incoming parameters
  2. The life cycle of this URL exists in the document it was created in
  3. Generally, you can preview binary data such as pictures, audio, and video in the browser without uploading to the server

usage

<!DOCTYPE html>
<html>
  <head>
    <title>Upload Image</title>
  </head>
  <body>
    <input type="file" name="imgFile" id="imgFile" onchange="changeFile()" />
    <br />
    <img id="previewImg" src="" alt="Preview Image" />
    <script>
      function changeFile() {
      
      
        const imgFile = document.getElementById('imgFile').files[0]; // 接口需要的参数 file类型的图片
        console.log(imgFile.size);
        if (imgFile.size > 1024 * 1024 * 2) return alert('不允许超过 2 M');
        const typeArr = ['image/png', 'image/jpeg', 'image/git', 'image/jpg'];
        if (!typeArr.includes(imgFile.type)) return alert('只支持jpg,png,jpeg,gif格式');
        // 生成预览图片地址:通过js将文件信息在本地电脑内存中变成一个预览地址临时拿去使用显示
        const imgUrl = URL.createObjectURL(imgFile);
        console.log(imgUrl); // blob:null/a0972036-a4b0-4821-9a0e-b2003797cb3d
        document.getElementById('previewImg').src = imgUrl;
      }
    </script>
  </body>
</html>

base64

insert image description here

  1. introduce

    1. Is a representation method based on 64 printable characters to represent binary data
    2. Applications that need to store and transmit binary data through uploads designed to 文本数据encode媒介
  2. Conversion method (js)

    1. atob():decoding
    2. btoa():coding
  3. Practical application scenarios

    1. Convert canvas to base64 encoded format picture

      const canvas = document.getElementById('canvas'); 
      const ctx = canvas.getContext("2d");
      const dataUrl = canvas.toDataURL();
      
    2. Convert pictures, files, etc. to base64 for transmission or storage

convert

file to base64

export const FileToBase64 = (file) => {
    
    
    return new Promise((resolve, reject) => {
    
    
        const reader = new FileReader();
        reader.onload = (e) => {
    
     
            resolve(e.target.result); 
        };
        reader.onerror = () => {
    
    
            reject();
        };
        reader.readAsDataURL(file);
    });
};

blob to base64

export const blobToBase64 = (blob) => {
    
    
    return new Promise((resolve, reject) => {
    
    
        const reader = new FileReader();
        reader.onload = (e) => {
    
     
            resolve(e.target.result); 
        };
        reader.onerror = () => {
    
    
            reject();
        };
        reader.readAsDataURL(blob);
    });
};

base64 to blob

export const base64ToBlob = (code) => {
    
    
    const parts = code.split(";base64,");
    const contentType = parts[0].split(":")[1];
    const raw = window.atob(parts[1]);
    const rawLength = raw.length;

    const uInt8Array = new Uint8Array(rawLength);

    for (let i = 0; i < rawLength; ++i) {
    
    
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {
    
     
        "type": contentType 
    });
};

baes64 to file

export const base64ToFile = (code, fileName) => {
    
    
    const parts = code.split(";base64,");
    const contentType = parts[0].split(":")[1];
    const fileExt = contentType.split("/")[1];
    const raw = window.atob(parts[1]);
    const rawLength = raw.length;

    const uInt8Array = new Uint8Array(rawLength);

    for (let i = 0; i < rawLength; ++i) {
    
    
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new File([uInt8Array], `${
      
       fileName }.${
      
       fileExt }`, {
    
     
        "type": contentType 
    });
};

blob to file

export const blobToArrayBuffer = (blob) => {
    
    
    return new Promise((resolve, reject) => {
    
    
        const reader = new FileReader();
        reader.onload = (e) => {
    
     
            resolve(e.target.result); 
        };
        reader.onerror = () => {
    
    
            reject();
        };
        reader.readAsArrayBuffer(blob);
    });
};

blob to ArrayBuffer

export const blobToArrayBuffer = (blob) => {
    
    
    return new Promise((resolve, reject) => {
    
    
        const reader = new FileReader();
        reader.onload = (e) => {
    
     
            resolve(e.target.result); 
        };
        reader.onerror = () => {
    
    
            reject();
        };
        reader.readAsArrayBuffer(blob);
    });
};

file to ArrayBuffer

export const fileToArrayBuffer = (file) => {
    
    
    return new Promise((resolve, reject) => {
    
    
        const reader = new FileReader();
        reader.onload = (e) => {
    
     
            resolve(e.target.result); 
        };
        reader.onerror = () => {
    
    
            reject();
        };
        reader.readAsArrayBuffer(file);
    });
};

Guess you like

Origin blog.csdn.net/qq_43382853/article/details/130235752