preface
The file API provided in HTML5 has rich applications in the front end, and uploading, downloading, and reading content are common in daily interactions. And in each browser compatibility is also better, including mobile terminal, except IE only support IE10 above version. To get a better handle on the functionality of manipulating files, familiarize yourself with each API.
FileList objects and file objects
The input[type=”file”] tag in HTML has a multiple attribute that allows the user to select multiple files, and a FileList object represents the list of files selected by the user. Each file in this list is a file object.
Properties of the file object:
- Name: indicates the file name, excluding the path.
- Type: indicates the file type. Image files start with image/, which allows you to restrict only images to be uploaded.
- Size: indicates the file size. Other operations can be performed depending on the file size.
- LastModified: The last time the file was modified.
<input type="file" id="files" multiple>
<script>
var elem = document.getElementById('files');
elem.onchange = function (event) {
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
// The file type is image and the file size is less than 200KB
if(files[i].type.indexOf('image/')! = =- 1 && files[i].size < 204800) {console.log(files[i].name); }}}</script>Copy the code
Input has an Accept attribute that can be used to specify the type of file that can be submitted via file upload.
Accept =”image/*” can be used to restrict only image formats to be uploaded. However, in Webkit, the response was slow, and it took several seconds for the file selection box to pop up.
The solution is to change the * wildcard to the MIME type specified.
<input type="file" accept="image/gif,image/jpeg,image/jpg,image/png">Copy the code
A Blob object
A Blob object acts as a container and can be used to store binary data. It has two properties, size for the byte length and TYPE for the MIME type.
How to create
Blob objects can be created using the Blob() constructor.
var blob = new Blob(['hello'] and {type:"text/plain"});Copy the code
The first argument in the Blob constructor is an array that can hold ArrayBuffer objects, ArrayBufferView objects, Blob objects, and strings.
A Blob object can be returned with a new Blob object via the slice() method.
var newblob = blob.slice(0.5, {type:"text/plain"});Copy the code
The slice() method takes three parameters, all of which are optional. The first parameter represents the start of the binary data in the Blob object, the second parameter represents the end of the replication, and the third parameter represents the MIME type of the Blob object.
Canvas.toblob () can also create Blob objects. ToBlob () takes three arguments, the first a callback function, the second an image type, which defaults to Image/PNG, and the third an image quality between 0 and 1.
var canvas = document.getElementById('canvas');
canvas.toBlob(function(blob){ console.log(blob); }, "image/jpeg".0.5);Copy the code
The download file
The Blod object can generate a network address from the window.URL object, which can be used to download files with the download attribute of the A tag.
For example, download canvas as an image file.
var canvas = document.getElementById('canvas');
canvas.toBlob(function(blob){
// Use createObjectURL to generate the address in blob format :null/ fd95b806-DB11-4f98-b2CE-5eb16b38ba36
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = 'canvas';
a.href = url;
// Simulate a TAB click to download
a.click();
// The download tells the browser that it no longer needs to keep a reference to the file
URL.revokeObjectURL(url);
});Copy the code
You can also save the string as a text file in a similar way.
FileReader object
The FileReader object is primarily used to read a file into memory and to read the data in the file. Create a FileReader object through the constructor
var reader = new FileReader();Copy the code
This object has the following methods:
- Abort: Breaks the read operation.
- ReadAsArrayBuffer: Reads the file contents into the ArrayBuffer object.
- ReadAsBinaryString: Reads the file as binary data.
- ReadAsDataURL: Reads the file as a string in the data: URL format.
- ReadAsText: Reads the file as text.
Upload image preview
A common application is to use readAsDataURL() to display an image after it has been uploaded by the client.
<input type="file" id="files" accept="image/jpeg,image/jpg,image/png">
<img src="blank.gif" id="preview">
<script>
var elem = document.getElementById('files'),
img = document.getElementById('preview');
elem.onchange = function () {
var files = elem.files,
reader = new FileReader();
if(files && files[0]){
reader.onload = function (ev) {
img.src = ev.target.result;
}
reader.readAsDataURL(files[0]); }}</script>Copy the code
But there is a bug on some phones where photos are upside-down when they are uploaded, including Samsung and iPhone… Solution here do not explain, interested can see: mobile end picture upload rotation, compression solution
Backup and restore data
The readAsText() function of the FileReader object can read the text of the file. Combined with the function of the Blob object to download the file, it is possible to back up the exported file to the local. When the data needs to be restored, the backup file can be uploaded through input. Use readAsText() to read the text and restore the data.
Code similar to the above function, not repeated here, the specific application can refer to: Notepad
Base64 encoding
Atob and BTOA methods have been added to HTML5 to support Base64 encoding. They are simply named B to A and A to B, which stands for encoding and decoding.
var a = "https://lin-xin.github.io";
var b = btoa(a);
var c = atob(b);
console.log(a); // https://lin-xin.github.io
console.log(b); // aHR0cHM6Ly9saW4teGluLmdpdGh1Yi5pbw==
console.log(c); // https://lin-xin.github.ioCopy the code
The btoa method encodes the string a without changing the value of a and returns an encoded value. The ATOB method decodes the encoded string.
However, if the parameter contains Chinese characters and exceeds the range of 8-bit ASCII characters, the browser will report an error. Therefore, encodeURIComponent encoding processing is required for Chinese first.
var a = Hello world.;
var b = btoa(encodeURIComponent(a));
var c = decodeURIComponent(atob(b));
console.log(b); // JUU1JTkzJTg4JUU1JTk2JUJEJTIwJUU0JUI4JTk2JUU3JTk1JThD
console.log(c); // Hello worldCopy the code