Today to sort out the FileReader and window. URL. CreateObjectURL, has long been at the time of upload pictures, under the preview picture with finishing today FileReader () constructor, The readAsDataURL method on the object can encode the file readAsDataURL,base64, which is convenient, but it seems to need to be compatible with browsers of higher versions. Some students also encounter that some pictures on mobile terminals are not displayed, because there is no picture type.

FileReader()

Let’s start by looking at some syntax for the FileReader() constructor. The FileReader object allows a Web application to asynchronously read the contents of a File (or raw data buffer) stored on the user’s computer, using a File or Blob object to specify which File or data to read.

The File object can be a FileList object returned by the user after selecting a File on an input element, or it can be generated by a drag-and-drop operation DataTransfer object, which can also be returned from mozGetAsFile() on an HTMLCanvasElement.

Important: FileReader is only used to read file contents from the user’s (remote) system in a secure manner. It cannot be used to simply read files by pathname from the file system. To read files by pathname in JavaScript, you should use a standard Ajax solution for server-side file reading, or CORS permissions if reading crosses domains.

The event processing

  • Filereader. onabort Handles abort events. This event is emitted when the read operation is interrupted.
  • Filereader. onerror Processes error events. This event is emitted when an error occurs in a read operation.
  • Filereader. onload Handles the load event. This event is emitted when the read operation is complete.
  • Filereader. onloadStart Handles the loadStart event. This event is emitted when the read operation begins.
  • Filereader. onLoadEnd Handles the loadEnd event. This event is emitted at the end of a read operation (either successful or failed).
  • FileReader. Onprogress Handles the progress event. This event is triggered when a Blob is read.

Function method

  • The readAsArrayBuffer() method is used to start reading the contents of the specified Blob or File. When the read operation is complete, the readyState becomes DONE and the Loadend event is fired, and the Result property contains an ArrayBuffer object representing the data from the read file.
  • The readAsBinaryString method reads the specified Blob or File object. When the read is complete, the readyState changes to DONE and the LoadEnd event is triggered. The Result property contains the original binary format of the read File.
  • The readAsDataURL method reads the specified Blob or File object. When the read operation is complete, readyState changes to DONE and the Loadend event is triggered, and the Result property contains a string in data:URL format (Base64 encoded) representing the contents of the read file.
  • The readAsText method converts a Blob or File object to its content (as a string) in a special encoding format. This method is asynchronous, meaning that the result is not visible until the execution is complete. This means that the onLoad or onLoadEnd method of the instance must be mounted to process the transformed result. When the conversion is complete, the readyState parameter is converted to the done state, the event mounted by event(” loadEnd “) is fired, and the filereader. result attribute is obtained from the parameters returned by the event

Here’s an example:

document.querySelector('input[type=file]').addEventListener('change', ()=>{ var reader = new FileReader(); ReadAsDataURL (files[0]); Reader.onload = (ev) => {console.log(ev) this.srcimgURL = reader.result // or const img = new Image() img.src = Reader. The result document. The body. The appendChild (img) / / reader. The result to obtain the results} reader. Onprogress = (ev) = > {/ / here is the progress in reading the file, Console. log(ev.loaded)}},false)
Copy the code

You can also read files

document.querySelector('input[type=file]').addEventListener('change', ()=>{ var reader = new FileReader(); ReadAsText (input.files[0],'utf8') 
    reader.onload = ()=>{
      document.body.innerHTML += reader.result  
    }
},false)
Copy the code

window.URL.createObjectURL(blob||file)

The url.createObjecturl () method creates a URL to the parameter object based on the parameter passed in. The URL lives only in the document in which it is created, and the new object URL points to the File object or Blob object being executed.

objectURL = window.URL.createObjectURL(blob || file);
Copy the code

A File object is a File. For example, if I upload a File with the input type=” File “tag, then every File in it is a File object.

Blob objects are binary data, such as objects created with new Blob().

Each time createObjectURL is called, a new URL object is created, even if you have already created a URL for the same file. If you no longer need the object, release it using the url.revokeobjecturl () method.

letSRC = url.createObjecturl (file)//file Indicates the uploaded image for inputlet img = new Image()
img.src = src
img.onload = () => {
    this.srcImgUrl = src
}
Copy the code

Monitoring upload Progress

If it’s Axios, we can monitor progress like this:

Const config = {onUploadProgress: e => {parseInt((e.loaded/e.total) * 100)}} axios.post('Interface address', formData, config)
Copy the code

It actually relies on the encapsulation of native Ajax, the onProgress method of native Ajax.

new XMLHttpRequest().onprogress = (e)=>{
     parseInt((e.loaded / e.total) * 100)
}

Copy the code

Drag an image to an area of the page to upload

The main action event is drop, but the browser has some default behavior, so clear the default behavior and cancel bubbling when dragging the mouse.

<div>
    <input type="file" @change="uploadPage" multiple accept=".png, .jpg, .gif" />
    <img :src="srcImgUrl" />
    <div class="drop" id="drop_area" :style="{'border-color': (borderhover ? '#3d8cff':'#BBBBBB')}">
    </div>
</div>

data() {
    return {
        srcImgUrl:' ',
        borderhover:false,}},mounted() {
    var dropbox = document.getElementById('drop_area');
    dropbox.addEventListener("drop",this.enentDrop,false)
    dropbox.addEventListener("dragleave".function(e) {// Drag away method e.topPropagation (); e.preventDefault(); this.borderhover =false;
    })
    dropbox.addEventListener("dragenter".function(e) {// Drop access to the method e.topPropagation (); e.preventDefault(); this.borderhover =true;
    })
    dropbox.addEventListener("dragover".function(e) {// Drag method e.topPropagation (); e.preventDefault(); this.borderhover =true
    })
},
methods:{
    enentDrop: function(e){this.borderhover = (){this.borderhover = ()false
        e.stopPropagation();
        e.preventDefault(); 
        letfileData = e.dataTransfer.files; //fileData is an uploaded image or file, then upload.......... }}Copy the code

When dragging the picture close to the set area, I marked the border blue here, at this time the mouse is still dragging state, here you can do as required.

Drag and drop is a new attribute added to HTML5 later, which is still convenient. Welcome to discuss it with interested students. If there are good suggestions, I will add them to the article.