_javascript tips for reading and saving file instances in JavaScript

Source: Internet
Author: User

Saying today is just a cursory glance at the source of proxy switchysharp, it has harvested a lot of things, including this article to introduce the reading and saving files.

Because Google does not yet provide the ability to sync plug-in data, importing and exporting plug-in configurations must be in contact with files. For security reasons, only IE provides access to the file's APIs, but with the advent of HTML 5, other browsers are supporting it.

First, read the file. The consortium provides some file APIs, the most important of which is the FileReader class.

First, list the HTML tags you want to use:

Copy 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) is passed as an argument to the Handlefiles () function.
This FileList object is like an array that knows the number of files, and its element is the file object.
From this file object you can get properties such as name, size, lastmodifieddate, and type.
This file object can be read by passing it to the Read method of the FileReader object.


There are 4 ways to read FileReader:
1.readAsArrayBuffer (file): Read the files as Arraybuffer.
2.readAsBinaryString (file): Read files as binary strings
3.readAsDataURL (file): Read files as data URL
4.readAsText (file, [encoding]): reads files as text, encoding defaults to ' UTF-8 '
In addition, the abort () method can stop reading files.


The FileReader object will need to be processed after the file is read. To not block the current thread, the API uses the event model to register these events:
1.onabort: Triggering 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, whether or not it fails
5.onloadstart: Trigger when file starts reading
6.onprogress: Periodically triggers when the file is read

With these methods, you can process the files.
Try to read the text file first:

Copy Code code 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);
}
}
}


Here the This.result is actually Reader.result, which is the content of the file read out.
Test you will find that the contents of this file have been added to the Web page. If you use chrome, you must put the Web page on the server or in the plugin, the file protocol will fail.

Try the picture again, because the browser can display a picture of the data URI protocol directly, so add the picture this time:

Copy Code code 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 () {
$ (' '). Appendto (' body ');
}
Reader.readasdataurl (file);
}
}
}

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

Copy Code code as follows:

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

In this way handlefiles () will need to traverse the processing files.

If you want to read only part of the data, the file object also has a webkitslice () or Mozslice () method for generating a Blob object. This object can be read filereader like a file object. These 2 methods receive 3 parameters: The 1th argument is the starting position, the 2nd is the ending position, the end of the file is omitted, and the 3rd is the content type.
Examples can refer to "Reading Local files in JavaScript."

Of course, in addition to importing data and displaying files, it can be used for Ajax uploads, and the code can refer to the Using files from Web applications.


Next, save the file.
In fact, the 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 unavailable.
For browsers that are not supported, you can use Blobbuilder.js and filesaver.js for support.
I studied for a moment and found 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 for this Blob object.
After you get the download address, create a a element, assign the download address to the href attribute, and the filename to the Download property (Chrome 14+ support).
Then create a click event and hand it over to the a element, which causes the browser to start downloading the Blob object.
Finally, use Url.revokeobjecturl () to release the object URL, notifying the browser that it is not necessary to continue referencing the file.

Here's the code for the simplification:

Copy Code code 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 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 are prompted to save a text file when you test. Chrome needs to put the Web page on a server or plugin.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.