JavaScript (6) reading and saving files with JavaScript

Source: Internet
Author: User
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 HTML5, other browsers also support this feature. Use JavaScript to read and save files

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:

 


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:

ReadAsArrayBuffer (file): Read the file as ArrayBuffer.

ReadAsBinaryString (file): reads a file as a binary string.

ReadAsDataURL (file): reads a file as a Data URL

ReadAsText (file, [encoding]): reads a file as text. The default value of encoding is '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:

Onabort: triggered upon interruption

Onerror: triggered when an error occurs

Onload: triggered when the file is successfully read.

Onloadend: triggered when the file is read, whether or not it fails

Onloadstart: triggered when the file starts reading

Onprogress: periodically triggered when a file is read.

With these methods, you can process files.

Read files

First try to read the text file:


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'); } 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:


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'); } 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:


 


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.

Save files

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:


Var BlobBuilder = BlobBuilder | WebKitBlobBuilder | javasblobbuilder; 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, instead of opening var slice = blob in the browser. slice | blob. webkitSlice | blob. required 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. initMouseEv Ent ('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.

Appendix: file Writing Tools (dry goods)

/*** Write File ** @ param fileName file name * @ param data file stream * @ param path write path * @ return boolean */public static boolean writeFile (String fileName, String data, string path) {try {// System. out. println ("fileContent:" + data); File file = new File (path + fileName); if (! File. exists () {file. createNewFile ();} FileOutputStream outStream = new FileOutputStream (file); outStream. write (data. getBytes (); outStream. flush (); outStream. close (); outStream = null; return (true);} catch (Exception e) {e. printStackTrace (); return (false );}}

Meiwenmeitu

The preceding section describes how to use JavaScript to read and save the content of a file. For more information, see PHP Chinese website (www.php1.cn )!

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.