Reading and saving file instances in JavaScript

Source: Internet
Author: User

Today, I just roughly browsed the source code of Proxy SwitchySharp and learned a lot, including reading and saving files described in this article.

Because Google does not provide the ability to synchronize plug-in data, you must deal with files when importing and exporting plug-in configurations. For security reasons, only Internet Explorer provides APIs for accessing files. However, with the advent of HTML 5, other browsers also support this feature.

First, 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 codeThe 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) is passed as a parameter to the handleFiles () function.
This FileList object is similar to an array. you can know the number of files, and its element is the File object.
You can obtain attributes such as name, size, lastModifiedDate, and type from this File object.
Pass the File object to the FileReader object reading method to read the File.


There are four read methods for FileReader:
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]): Read the file as text, and encoding defaults to 'utf-8'
In addition, the abort () method can stop reading files.


The FileReader object still needs to be processed after reading the file. To avoid blocking the current thread, the API uses the event model and can register these events:
1. onabort: triggered upon interruption
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: triggered when the file starts reading
6. onprogress: triggered periodically when the file is read.

With these methods, you can process files.
First try to read the text file:

Copy codeThe 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 (){
$ ('<Pre>' + this. result + '</pre>'). appendTo ('body ');
}
Reader. readAsText (file );
}
}
}


Here this. result is actually reader. result, that is, the content of the file read.
After testing, you will find that the content of this file has been added to the webpage. If Chrome is used, the webpage must be placed on the server or plug-in, and the file protocol will fail.

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

Copy codeThe 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 (){
$ ('<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 codeThe Code is as follows:
<Input type = "file" id = "files" multiple = "" onchange = "handleFiles (this. files)"/>

In this way, you need to traverse and process files in handleFiles.

If you only want to read part of the data, the File object also has the webkitSlice () or elastic slice () method, which is used to generate the Blob Object. This object can be read by FileReader like a File object. The two methods receive three parameters: 1st parameters are the starting position, 2nd are the Ending position, and when omitted, they are read to the end of the file; and 3rd are content type.
For examples, see Reading local files in JavaScript.

Of course, in addition to importing data and displaying files, it can also be used for AJAX upload. For the code, see Using files from web applications.


Next, save the file.
In fact, File API: Writer provides four interfaces, but currently only some browsers (Chrome 8 + and Firefox 4 +) Implement BlobBuilder, and other interfaces are unavailable.
For unsupported browsers, you can use BlobBuilder. js and FileSaver. js for support.
I have studied and discovered the mysteries.

BlobBuilder can create a Blob Object. Pass this Blob object to the URL. createObjectURL () method to get an object URL. The object URL is the Blob object.
After obtaining this information, create an a element and assign it to the href attribute. The file name is assigned to the download attribute (supported by Chrome 14 + ).
Then create a click event and hand it to the element for processing. This will cause the browser to start downloading the Blob Object.
Finally, use URL. revokeObjectURL () to release the object URL, notifying the browser that the file does not need to be referenced.

The following is a simplified code:
Copy codeThe Code 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 a browser
Var slice = blob. slice | blob. webkitSlice | blob. Batch slice;
Blob = slice. call (blob, 0, blob. size, force_saveable_type );
}

Var url = URL. createObjectURL (blob );
Var save_link = document. createElementNS ('HTTP: // www.w3.org/5o/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, 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 ');


During the test, you will be prompted to save a text file. Chrome needs to put the webpage on the server or plug-in.

Related Article

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.