Blob

A Blob object represents an immutable, raw data-like file object.

The basic use

grammar

const blob = new Blob(array, options)

parameter

  • Array is a collection ofArrayBuffer, ArrayBufferView, Blob, DOMStringAnd so on,DOMStringsIt’s going to be encoded utF-8.
  • Options is optional and may specify the following two properties:
    • Type. The default value is"", the MIME type of the content.
    • Hamid, the default value is"transparent"To specify the inclusion line terminator\nHow the string is written. It is one of two values:"native", indicating that the end-of-line character is changed to a newline suitable for the host operating system file system, or"transparent", which means that the terminator saved in the BLOB is kept unchanged

Instance properties, methods

  • typetypeCommon MIME types
  • sizeSize, in bytes
  • slice()BlobAnd return a new oneBlobArray, array, arrayslice)
  • arrayBuffer()Returns a binary representation ofpromise
  • stream()Returns aReadableStreamobject
  • text()Returns a textpromise

The last three methods are less compatible

The sample

    const blob1 = new Blob(['hello blob'] and {type: 'text/plain'})
    console.log(blob1) // Blob {size: 10, type: "text/plain", slice: function}

    const blob2 = new Blob([JSON.stringify({ a: 1 }, null.2)] and {type: 'application/json'})
    console.log(blob2) // Blob {size: 12, type: "application/json", slice: function}

    const blob3 = blob2.slice(0.5)
    console.log(blob3) // Blob {size: 5, type: "", slice: function}
Copy the code

Application scenarios

  • Upload files and fragments

    See Use of File

  • File preview and download

  <! -- File preview -->
  <canvas id="canvas"></canvas>
  <script>
    const canvas = document.querySelector('#canvas')
    const ctx = canvas.getContext('2d');

    ctx.fillStyle = 'green';
    ctx.fillRect(10.10.150.100);

    // toDataURL
    // Data url generates snippets of code corresponding to the image, which can be used anywhere (base64)
    createImg(canvas.toDataURL('image/png'))
    function createImg(url) {
      console.log(url)
      const img = document.createElement('img')
      img.src = url
      document.body.appendChild(img)
    }

    // toBlob
    canvas.toBlob((blob) = > {
      // The blob URL is only used under the current window, the url's life cycle and the Document binding in the window that created it
      const url = window.URL.createObjectURL(blob)
      console.log(url)
      const img = document.createElement('img')
      img.onload = () = > {
        // Remove if appropriate to prevent memory leaks
        window.URL.revokeObjectURL(url)
      }
      img.src = url
      document.body.appendChild(img)

      // Blob to data url with FileReader (base64)
      // Data url generates snippets of code corresponding to the image, which can be used anywhere (base64)
      const render = new FileReader()
      render.onload = ({target: { result }}) = > {
        console.log(result, 'FileReader')
      }
      render.readAsDataURL(blob)
    })

  </script>
  
  <! -- File download -->
  <script>
    / / TXT file
    const fileContent1 = new Blob(['hello world'.'hello blob'])
    const downloadText1 = document.createElement('a')
    const href1 = downloadText1.href = window.URL.createObjectURL(fileContent1)
    downloadText1.download="1.txt"
    downloadText1.innerText = 'download 1.txt'
    downloadText1.onclick = () = > {
      // You can't delete it
      // window.URL.revokeObjectURL(href1)
    }
    document.body.appendChild(downloadText1)

    document.body.appendChild(document.createElement('br'))

    / / CSV file
    const csvData =  [
      [The '#'.'name'.'age'],
      [1.'Joe'.20],
      [2.'Owen'.22],
      [3.'Tom'.18]]const fileContentExcel = new Blob(csvData.map(item= > `${item.join(', ')}\n`))
    const downloadText2 = document.createElement('a')
    const href2 = downloadText2.href = window.URL.createObjectURL(fileContentExcel)
    downloadText2.download="1.csv"
    downloadText2.innerText = 'download 1.csv'
    downloadText2.onclick = () = > {
      // You can't delete it
      // window.URL.revokeObjectURL(href2)
    }
    document.body.appendChild(downloadText2)
  </script>
Copy the code

File

File An object that describes File information that can be accessed by JavaScript, previewed, or submitted to the server. File inherits from Blob

The basic use

grammar

const file = new File(bits, name[, options])

parameter

  • Array is a collection ofArrayBuffer, ArrayBufferView, Blob, DOMStringAnd so on,DOMStringsIt’s going to be encoded utF-8.
  • Name Indicates the file name or file path.
  • Options is optional and may specify the following two properties:
    • Type. The default value is"", the MIME type of the content.
    • LastModified: value representing the Unix timestamp in milliseconds when the file was lastModified. The default is date.now ().

Instance properties, methods

  • inheritanceBlobAll properties and methods of
  • lastModifiedLast Modified time

The scenario where the File object is generated

  • new File()The constructor
  • through<input type="file" />Access to the file
  • Free drag and drop operation generatedDataTransferobject
  • throughCanvasmozGetAsFile()API to generateHas been out of date

Scenarios where File objects are used

  • FileRenderUse FileRender to convert to data URL (base64), text, etc
  • URL.createObjectURL()Generate bloB URL for online preview
   <input type="file" onchange="handlechange(event)" />
   <script>
     function handlechange(event) {
       const {
         target: { files },
       } = event;
       const file = files[0];

       preview(file);
     }
     
     function preview(file) {
       const { type } = file;
       if(! type.startsWith("image")) return;

       const url = window.URL.createObjectURL(file);
       const img = document.createElement("img");
       img.onload = () = > {
         // Remove if appropriate to prevent memory leaks
         window.URL.revokeObjectURL(url);
       };
       img.src = url;
       document.body.appendChild(img);
     }
   </script>
Copy the code
  • createImageBitmap()Cut the imagePoor compatibility
  // Clipping image to upload process (this method is not compatible, recommend using canvas clipping)
  // Image dom -> Clipping -> Canvas -> toBlob() -> Ajax upload
  createImageBitmap(img, 0.0.32.32).then((res) = > {
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");
    ctx.drawImage(res, 0.0);
  });
Copy the code
  • XMLHttpRequest.send()upload
   <input type="file" onchange="handlechange(event)" />
   <script>
     function handlechange(event) {
       const {
         target: { files },
       } = event;
       const file = files[0];

       uploadFile(file);
       preview(file);
     }

     function uploadFile(file) {
       const formData = new FormData();

       formData.append(
         "content",
         file
       );
       fetch("http://localhost:3000/upload-file", {
         method: "post".body: formData,
       })
         .then((res) = > res.json())
         .then((res) = > {
           console.log(res, "res");
         });
     }

     function preview(file) {
       const { type } = file;
       if(! type.startsWith("image")) return;

       const url = window.URL.createObjectURL(file);
       const img = document.createElement("img");
       img.onload = () = > {
         // Remove if appropriate to prevent memory leaks
         window.URL.revokeObjectURL(url);
       };
       img.src = url;
       document.body.appendChild(img);
     }
   </script>
Copy the code

ArrayBuffer

The ArrayBuffer object is used to represent a generic, fixed-length buffer of raw binary data. You cannot manipulate the contents of an ArrayBuffer directly, but rather through a type array object or DataView object

ArrayBuffer document

FileRender

Blob or File to text, data URL (base64), ArrayBuffer – Blob or File to text, data URL (base64), ArrayBuffer

Use File to base64 as shown above

FormData

A data format used for uploading forms

Use file upload as shown above

conclusion

  • Blob, ArrayBuffer, FileIt’s all binary data
  • FileRenderConversion tool
  • FormDataCommunication data format

We can set it when we do AjaxresponseTypeblob,ArrayBufferThe back end returns the stream and the front end handles it.

Post to recommend

  • Vue + TypeScript + Element-UI + Axios builds the front-end project infrastructure
  • Realize project download, automatic routing and project release scaffolding based on Node
  • Encapsulate a simple WebSocket library
  • Note: Vue often meet questions summary and analysis
  • Proxy is an alternative to Object. DefineProperty in Vue3.0
  • Vue 3.0 – First experience 1
  • Figure out a prototype, a prototype object, a prototype chain
  • Promise Principles = Build a Promise from 0 to 1

[Notes are not easy, if it is helpful to you, please like, thank you]