Read and save file instances in JavaScript

  • 2020-03-30 02:49:57
  • OfStack

First, read the file. The W3C provides several File apis, the most important of which is the FileReader class.

List the required HTML tags:

<input type="file" id="file" onchange="handleFiles(this.files)"/>

When a file is selected, the list containing the file (a FileList object) is passed to the handleFiles() function as an argument.
The FileList object is like an array that knows the number of files, and its elements are the File object.
From this File object you can get attributes such as name, size, lastModifiedDate, and type.
Pass the File object to the read method of the FileReader object to read the File.


There are four ways to read FileReader:
1. ReadAsArrayBuffer (file) : reads a file as an ArrayBuffer.
2. ReadAsBinaryString (file) : reads a file as a binary string
3. ReadAsDataURL (file) : reads the file as a DataURL
4. ReadAsText (file, [encoding]) : reads the file as text with the encoding default of 'utf-8'
In addition, the abort() method can stop reading a file.


The FileReader object also needs to be processed after the file has been read. In order not to block the current thread, the API USES an event model, and you can register these events:
1. Onabort
2. Onerror: triggered when something goes wrong
3. Onload: triggered when the file is successfully read
Onloadend: triggered when the file is read, whether or not it fails
5. Onloadstart: triggered when the file starts to be read
6. Onprogress: triggered periodically when a file is read

With these methods in place, you can work with files.
Try reading a text file first:


function handleFiles(files) {
    if (files.length) {
        var file = files[0];
        var reader = new FileReader();
        if (/text/w+/.test(file.type)) {
            reader.onload = function() {
                $('<pre>' + this.result + '</pre>').appendTo('body');
            }
            reader.readAsText(file);
        }
    }
}


This. Result here is actually the reader.result, which is the contents of the file read out.
Test this and you will find that the contents of this file have been added to the web page. If you're using Chrome, you have to put the web page on a server or in a plug-in, which fails under the file protocol.

Try the image again, because the browser can directly display the Data URI protocol image, so this time add the image:


function handleFiles(files) {
    if (files.length) {
        var file = files[0];
        var reader = new FileReader();
        if (/text/w+/.test(file.type)) {
            reader.onload = function() {
                $('<pre>' + this.result + '</pre>').appendTo('body');
            }
            reader.readAsText(file);
        } else if(/image/w+/.test(file.type)) {
            reader.onload = function() {
                $('<img src="' + this.result + '"/>').appendTo('body');
            }
            reader.readAsDataURL(file);
        }
    }
}


<input type="file" id="files" multiple="" onchange="handleFiles(this.files)"/>

In this case, handleFiles() needs to be traversed to process files.

The File object also has webkitSlice() or mozSlice() methods for generating Blob objects if you just want to read part of the data. This object can be read by FileReader just like a File object. The two methods receive three parameters: the first parameter is the starting position; The second is the end of the position, when omitted will read to the end of the file; The third one is content type.
For an example, see Reading local files in JavaScript.

Of course, in addition to importing data and displaying files, it can also be used to do AJAX uploads, for example, Using files from web applications.

Here's a simplified version of the code:


var BlobBuilder = BlobBuilder || WebKitBlobBuilder || MozBlobBuilder;
var URL = URL || webkitURL || window;
function saveAs(blob, filename) {
    var type = blob.type;
    var force_saveable_type = 'application/octet-stream';
    if (type && type != force_saveable_type) { //Force the download instead of opening it in a browser
        var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
        blob = slice.call(blob, 0, blob.size, force_saveable_type);
    }
    var url = URL.createObjectURL(blob);
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = url;
    save_link.download = filename;
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
    URL.revokeObjectURL(url);
}
var bb = new BlobBuilder;
bb.append('Hello, world!');
saveAs(bb.getBlob('text/plain;charset=utf-8'), 'hello world.txt');


The test prompts you to save a text file. Chrome requires web pages to be placed on a server or in a plug-in.


Related articles: