This is the 18th day of my participation in Gwen Challenge

Relearn JavaScript in a series of articles…

Reading a file, we started with an input tag, which looks like this:

<body> <input type='file' onchange="fileChange(this)"/> <script> function fileChange(target) Target. files[0] var fileInfo = 'Filename :'+file.name+' Type :'+file.type+' file size :'+file.size+' last modified time :'+file.lastModifiedDate console.log(fileInfo) } </script> </body>Copy the code

The File API now provides a more secure way to access client files, and even read the data in the File through FileReader.

FileReader

FileReader is an asynchronous file reading mechanism.

It has the following methods:

  1. ReadAsText (file,encoding) : Reads the file as plain text
  2. ReadAsDataURL (file) : Reads the file and saves the file as a data URI to Result
  3. ReadAsBinaryString (file) : Reads the file and stores a string in the Result property, where each character represents a byte
  4. ReadAsArrayBuffer (file) : Reads the file and saves an ArrayBuffer containing the contents of the file to the result property

It has the following events:

  1. Progress: indicates that the data is read again and is triggered at about 50ms
  2. Error: An error is triggered
  3. Load: Has read the entire file trigger
  4. Abort: interrupts the read process
  5. Loadend: Indicates that the load, error, and abort events are triggered after the whole process ends

Here’s an example:

<body> <input type='file' onchange="fileChange(this)"/> <div id='output' /> <script> function fileChange(target){ // Var file = target.files[0],  output = document.getElementById('output'), type = '', reader = new FileReader(); if(/image/.test(file.type)){ type = 'image' reader.readerAsDataURL(file) }else{ type = 'text' reader.readAsText(file) } Onprogress = function(e){if(e.logthcomputable){console.log(' the current load progress is ':e.loaded+'/'+e.total)}} // Reader.onerror = function(){// 1: File not found 2: security error 3: read interrupt 4: Var errCode = reader.error. Code} // Reader.onload = function(){// reader.result: Var HTML = type==='image'? <img SRC ='${reader.result}'> ':reader.result output.innerhtml = HTML} reader.onloadEnd = function(){}} </script> </body>Copy the code

Read part of file

File objects support a slice() method that takes two parameters: the start byte and the number of bytes to read. Return an instance of Blob, the parent of the File type.

Sample pseudocode:

Function blobSlice(blob,start,length){if(blob.slice){return blob.slice(start,length)}else if(blob.webkitSlice){ return blob.webkitSlice(start,length) }else if(blob.mozSlice){ return blob.mozSlice(start,length) }else{return null}} Var reader = new FileReader() var file = target.files[0] var blob = blobSlice(file,0,32) reader.readAsText(blob)Copy the code

Object URL

Object urls, also known as BLOB urls, refer to urls that reference data stored in a File or BLOb. The advantage is that you don’t have to read the file content into JavaScript to use it directly. Of course, free up the URL space when not in use.

Example pseudocode is as follows:

/ / create the URL object function createObjectUrl (blob) {if (window. URL) {return window. URL. CreateObjectUrl (blob)} the else If (window. WebkitURL) {return window. WebkitURL. CreateObjectURL (blob)} else {return}} / / destroyed the URL object function revokeObjectURL(url){ if(window.URL){ window.URL.revokeObjectURL(url) }else if(window.webkitURL){ Window. WebkitURL. RevokeObjectURL (url)}} / / hypothesis for the picture file object var file = target. The files [0] / / var url = create pictures url object CreateObjectUrl (file) var HTML = '<img SRC ="${url}"/>' revokeObjectURL(url)Copy the code

Drag files to upload

Combining the H5 drag-and-drop API with the file API creates a compelling user interface. Here is the basic flow code:

var oBox = document.getElementById('box'); var oM = document.getElementById('m1'); var timer = null; Document.ondragover = function(){console.log(' file coming ')}; OBox. Ondragenter = function(){oBox. InnerHTML = 'Please release the mouse '; }; oBox.ondragover = function(){ return false; }; Obox.ondragleave = function(){obox.innerhtml = 'Please drag the file to this section '; }; oBox.ondrop = function(ev){ var file = ev.dataTransfer.files[0]; var reader = new FileReader(); Onload = function(){console.log(reader); Var form = new FormData() form.append('file',file)... }; Reader.onloadstart = function(){console.log(' start reading '); }; Reader.onloadend = function(){console.log(' read finished '); }; Reader.onabort = function(){console.log(' abort '); }; Reader.onerror = function(){console.log(' failed to read '); }; Reader. onprogress = function(e){console.log(' current load progress ':e.loaded+'/'+e.total)}; };Copy the code

conclusion

So far we have learned about the File API.