Young boy, I see your skeleton fine and strange, is all in the martial arts prodigy, I have this “picture flow” secret book, see and you have destiny, send to you.

Image flow

The image stream referred to in this article is to read local images and display them on the page using a file stream.

First, let’s briefly describe several ways to upload files, and then implement them in turn

Upload the way

input

Create and listen for the change event to obtain the file object as follows

click = (a)= > {
    let input = document.createElement('input')
    input.setAttribute('type'.'file')
    input.setAttribute('accept'.'image/*')
    
    input.onchange = event= > {
        let file = event.target.files[0]
    }
    
    input.click()
    
} 
Copy the code

Drag && drop

Using HTML5’s drag-and-drop API, listen for the element’s drop event, again fetching the File object

A DataTransfer object is created, which we’ll encounter again later

dragover = event= > {
   event.preventDefault()
}

drop = event= > {
    event.preventDefault()
    let files =  event.dataTransfer.files
}
Copy the code

paste

Bind elements to paste events. Thanks to Contenteditable we can add to all elements, but waves still sound, and get the files contained in the event

paste = (e) = > {
    e.preventDefault()
    let file = e.clipboardData.files[0]}Copy the code

clipboardData

Paste event provides a clipboardData property, which is an object of type DataTransfer. As we mentioned earlier, drag and drop produces a DataTransfer object, and yes, paste too.

Here and there, lifting her veil.

As you can see above, clipboardData has the following properties

  • DropEffect is node by default
  • Effectalhoward is uninitialized by default
  • Files List of local files
  • Items Items in the clipboard
  • Types Each data type in the clipboard

We just need to use files, the image file is inside it

The file format

file

Typically, a File object is a FileList object returned by the user after selecting a File on an element, or it can be a DataTransfer object generated by a drag-and-drop operation, inherited from a Blob

That’s what it looks like, Noe.

You can see the following attributes:

  • Name: indicates the file name. This property is read-only.
  • Size: indicates the file size, in bytes. This property is read-only.
  • Type: MIME type of the file. If the type is not discernible, it is an empty string. This property is read-only.
  • LastModified: time when the file was lastModified. The format is timestamp.
  • LastModifiedDate: Time when the file was last modified in the format of Date object instance.

We won’t delve too deeply into the File object, except that it allows access to local files.

blob

A Blob object represents an immutable, raw data-like file object. The data represented by a Blob is not necessarily a JavaScript native format. The File interface is based on Blob, inheriting Blob functionality and extending it to support files on the user’s system.

Create a BLOB object

var aBlob = new Blob( array, options );
Copy the code
  • An array is an array made up of objects such as ArrayBuffer, ArrayBufferView, Blob, DOMString, etc., or a mixture of similar objects that will be put into the Blob.

  • Options is an optional Blob familiarity dictionary that may specify two properties

    • Type, which defaults to “”, represents the MIME type of the array content to be put into the BLOB.

    • The default value of endings is “transparent”, which means how the string with the line end \n is output.

var a = ["hello"."world"];
var myBlob = new Blob(a, { "type" : "text/xml" });
console.log(myBlob);
Copy the code

By creating bloBs on the fly, we can achieve pure front-end downloads

const foo = {hello: "world"};
const blob = new Blob([JSON.stringify(foo)], {type: "text/plain"});
const fileName = `The ${Date.now()}.doc`;
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
URL.revokeObjectURL(link.href);
Copy the code

Blob URL

Blob URL is the URL of the Blob protocol in the following format

blob:http://localhost:1234/946644c4-ca98-405e-918c-759e790d0330
Copy the code

Blob urls can be created with url.createObjecturl (Blob), and every time the createObjectURL() method is called, a new URL object is created, even if you already created it with the same object as an argument.

RevokeObjectURL (objectURL) releases URL objects when they are no longer needed

To display a local image using a Blob URL, we simply assign the URL we created to the SRC property of img.

FileReader

FileReader is used to read file or BLOB data asynchronously, depending on the file size.

let render = new FileReader()
render.onload = () => {
    let src = render.result
}
render.readAsDataURL(file)
Copy the code

FileReader Method of reading files

  • ReadAsBinaryString file Reads the file as binary encoding

  • ReadAsBinaryArray file Reads a file as a binary array

  • ReadAsText file[, encoding] reads the file as text according to the format, encode defaults to UTF-8

  • ReadAsDataURL file Reads the file as DataUrl

base64

Using FileReader to read the file, you can read the image in Base64 format.

Simply assign result to SRC in the onload function of the FileReader instance

Format differences

There are two main formats, base64 and BLOB, and the differences between them are as follows

  • Blob urls are generally short in length

  • Blob urls make it easy to get source data using XMLHttpRequest, and Base64 is not supported by all browsers

  • Blob urls can only be used within the current application

Format to format conversion

Canvas becomes bloB object

canvas.toBlob(function (blobObj) {
	console.log(blobObj)
})
Copy the code

Canvas into base64

let imgSrc = canvas.toDataURL('image/png')
Copy the code

Base64 into a blob

function dataURLtoBlob(dataurl) {
  let arr = dataurl.split(",");
  let mime = arr[0].match(/ : (. *?) ; /) [1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }

  return new Blob([u8arr], { type: mime });
}

Copy the code

reference

The front-end uses Blob objects to create and download specified files

Conversions between DataURL and File,Blob, and Canvas objects

At the end

Text complete code, please stamp github

Have a great weekend, everyone.