By the way, today I just browsed the source code of Proxy SwitchySharp and gained a lot of things, including reading and saving files to be introduced in this article.
Because Google does not provide the function of synchronizing plug-in data, importing and exporting plug-in configurations must be dealt with files. For security reasons, only IE provides an API to access files; but with the arrival of HTML 5, other browsers have also supported it.
First, let’s talk about reading the file. W3C provides some File APIs, the most important of which is the FileReader class.
First list the HTML tags you need:
Copy the code code as follows:<input type="file" id="file" onchange="handleFiles(this.files)"/>
When a file is selected, the list containing the file (a FileList object) will be passed as a parameter to the handleFiles() function.
This FileList object is similar to an array, which can tell 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 this File object to the read method of the FileReader object and you can read the file.
There are 4 reading methods in FileReader:
1. readAsArrayBuffer(file): Read the file as an ArrayBuffer.
2. readAsBinaryString(file): read the file as a binary string
3.readAsDataURL(file): Read the file as Data URL
4. readAsText(file, [encoding]): reads the file as text, the default encoding value is 'UTF-8'
In addition, the abort() method can stop reading the file.
The FileReader object needs to be processed after reading the file. In order not to block the current thread, the API adopts an event model, which can register these events:
1.onabort: Triggered when interrupted
2.onerror: Triggered when an error occurs
3.onload: Triggered when the file is successfully read
4.onloadend: Triggered when the file is read, regardless of whether it fails or not
5.onloadstart: Triggered when the file starts reading
6.onprogress: triggers periodically when the file is read
With these methods, you can process the files.
Let's try reading text files first:
The code copy is as follows:
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 reader.result, which is the read file content.
After testing, you will find that the contents of this file have been added to the web page. If you are using Chrome, you must put the web page on the server or in the plug-in, and the file protocol will fail.
Let’s try the pictures again, because the browser can directly display the pictures of the Data URI protocol, so add the pictures this time:
The code copy is as follows:
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);
}
}
}
In fact, the input:file control also supports selecting multiple files:
The code copy is as follows:
<input type="file" id="files" multiple="" onchange="handleFiles(this.files)"/>
In this way, handleFiles() needs to be traversed to process files.
If you want to read only part of the data, the File object also has webkitSlice() or mozSlice() methods, which are used to generate Blob objects. This object can be read by FileReader just like the File object. These two methods receive 3 parameters: the first parameter is the starting position; the second is the end position, and when omitted, the end of the file is read; the third is the content type.
For examples, please refer to "Reading local files in JavaScript".
Of course, in addition to importing data and displaying files, it can also be used for AJAX upload. The code can be used to refer to "Using files from web applications".
Next, save the file.
In fact, File API: Writer provides 4 interfaces, but currently only some browsers (Chrome 8+ and Firefox 4+) implement BlobBuilder, and the rest of the interfaces are not available.
For unsupported browsers, you can use BlobBuilder.js and FileSaver.js to get support.
I studied it and discovered the mystery.
BlobBuilder can create a Blob object. Pass this Blob object to the URL.createObjectURL() method and you can get an object URL. And this object URL is the download address of this blob object.
After getting the download address, create an element a, assign the download address to the href attribute, and assign the file name to the download attribute (supported by Chrome 14+).
Then create a click event and hand it over to this a element to process, which will cause the browser to start downloading the blob object.
Finally, use URL.revokeObjectURL() to release the object URL, notifying the browser that it does not have to continue to reference the file.
Here is a simplified code:
The code copy is as follows:
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 download, not open in the 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, 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');
A text file will be prompted to save during testing. Chrome needs to place web pages on the server or in the plug-in.