Home > Web Front-end > JS Tutorial > Examples of reading and saving files in JavaScript_javascript skills

Examples of reading and saving files in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:49:33
Original
1242 people have browsed it

By the way, I just took a cursory glance at the source code of Proxy SwitchySharp today, and I learned a lot, including reading and saving files that I will introduce in this article.

Because Google does not yet provide the function of synchronizing plug-in data, importing and exporting plug-in configurations must deal with files. For security reasons, only IE provides an API for accessing files; but with the arrival of HTML 5, other browsers have also supported it.

First let’s read the file. W3C provides some File APIs, the most important of which is the FileReader class.

First list the HTML tags that need to be used:

Copy the code The code is 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 to the handleFiles() function as a parameter.
This FileList object is similar to an array, you can know the number of files, and its elements are File objects.
Attributes such as name, size, lastModifiedDate and type can be obtained from this File object.
Pass this File object to the read method of the FileReader object to read the file.


FileReader has 4 reading methods:
1.readAsArrayBuffer(file): Read the file as ArrayBuffer.
2.readAsBinaryString(file): Read the file as a binary string
3.readAsDataURL(file): Read the file as a Data URL
4.readAsText(file, [encoding]): The file is read as text, and the default encoding value is 'UTF-8'
In addition, the abort() method can stop reading the file.


After reading the file, the FileReader object still needs to be processed. In order not to block the current thread, the API adopts an event model, and you can register these events:
1.onabort: Triggered when interrupted
2.onerror: Triggered when an error occurred
3.onload: When the file is successfully read Trigger
4.onloadend: Triggered when the file is read, regardless of failure
5.onloadstart: Triggered when the file starts to be read
6.onprogress: Triggered periodically when the file is read

With these methods, you can process files.
Let’s try reading a text file first:

Copy code The code 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() {
                   $('
' this.result '
').appendTo('body');
}
}
}


This.result here is actually reader.result, which is the read file content.

Test it and you will find that the content of this file is added to the web page. If you are using Chrome, you must put the web page on the server or in a plug-in. The file protocol will fail.

Let’s try pictures again, because the browser can directly display pictures of the Data URI protocol, so I will add pictures this time:

Copy code The code is as follows:

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



In fact, the input:file control also supports selecting multiple files:


Copy code

The code is as follows:
In this way, handleFiles() needs to traverse and process files.

If you only want to read part of the data, the File object also has webkitSlice() or mozSlice() methods for generating Blob objects. This object can be read by FileReader in the same way as the File object. These two methods receive 3 parameters: the first parameter is the starting position; the second parameter is the end position, if omitted, it will read to the end of the file; the third parameter 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. For code, please refer to "Using files from web applications".

The next step is to save the file.
Actually 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 gain support.

I researched it and discovered the secret.

BlobBuilder can create a Blob object. Pass this Blob object to the URL.createObjectURL() method to get an object URL. And this object URL is the download address of this Blob object.
After getting the download address, create an a element, 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 the a element for processing, which will cause the browser to start downloading the Blob object.
Finally, use URL.revokeObjectURL() to release the object URL and notify the browser that it no longer needs to reference this file.

The following is a simplified code:




Copy the code


var type = blob.type;
var force_saveable_type = 'application/octet-stream';
if (type && type != force_saveable_type) { // Force download instead of opening in 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');


You will be prompted to save a text file during testing. Chrome needs to put the web page on the server or in a plug-in.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template