JavaScript file processing: file read

Source: Internet
Author: User

In my previous blog, I described how to use files in JavaScript, with a specific focus on how to get the file object. Only when the user uploads the file by uploading or dragging it, these objects have the metadata of the file. Once you have these files, the next step is to read the data from these files.

FileReader Type

The FileReader type has a single job of reading data from a file and storing it in a JavaScript variable. Its APIs are intentionally designed to be the same as XMLHttpRequest because they all load data from an external resource (outside the browser). The read operation is asynchronous so that it does not clog the browser.

FileReader can create multiple formats to represent the data of a file, and the format that is returned when the file is read is required. The read operation is done by invoking either of the following methods:

    • readastext () – Returns the contents of the file using plain text
    • Readasbinarystring () – Returns the contents of the file using the encrypted binary data string (this method is deprecated, use Readasarraybuffer () instead)
    • readasarraybuffer () – Returns the contents of the file in the form of arraybuffer (useful for binary data than a file)
    • readasdataurl () – Returns the contents of the file using the data URL

The Send method, like the Xhr object, initiates an HTTP request, and each of the above methods initiates a file read. In this case, before you start reading, you must listen to the Load event, and Event.target.result always returns the read result. For example:

var reader = new FileReader (); reader.onload = function (event) {var contents = Event.target.result; Console.log ("File contents:" + contents);}; Reader.onerror = function (event) {Console.error ("File could not being read! Code "+ Event.target.error.code);}; Reader.readastext (file);

In this example, we simply read the contents of the file and output the contents to the console in plain text. The onload operation is called when the file is read successfully, and the onerror operation is called when it cannot be read for some reason. The FileReader instance can be obtained through Event.target in the event handler, and it is recommended to use this instead of directly using the reader variable. The result property contains the file contents when the read was successful and the error message when the read failed.

Read Data URI

You can use a similar method to read the file as a data URI, the data URI (sometimes called the data URL) is an interesting option, such as you want to display the image file read from disk, you can do this with the following code:

var reader = new FileReader (); reader.onload = function (event) {var Datauri = event.target.result, img =    Document.createelement ("img");    IMG.SRC = Datauri; Document.body.appendChild (IMG);}; Reader.onerror = function (event) {Console.error ("File could not being read! Code "+ Event.target.error.code);}; Reader.readasdataurl (file);

This code simply inserts an image file on the page that is read from the disk. Because this data URI contains all the data of the image, it can be passed directly to the SRC attribute of the image and displayed on the page. Alternately, you can load the image and draw it to a <canvas>:

var reader = new FileReader (); reader.onload = function (event) {    var Datauri = event.target.result,& nbsp       context = document.getElementById ("MyCanvas"). GetContext ("2d"),        img     = New Image ();   /wait until the Image has been fully processed     Img.onload = function () {        context.drawimage (img, +, +);  & nbsp };    IMG.SRC = Datauri;}; Reader.onerror = function (event) {    Console.error ("File could not being read! Code "+ Event.target.error.code);}; Reader.readasdataurl (file);

This code loads the image data into a new image object and draws it to a canvas (both width and length are specified as 100).

Data URIs are generally used to do this, but can be used on any type of file. The most common use of reading a file as a data URI is to quickly display the contents of a file in a Web page.

Read Arraybuffers

arraybuffer type [1] was originally introduced as part of WebGL. A arraybuffer represents a finite number of bytes that can be used to store numbers of any size. The way a Arraybuffer data is read requires a particular view, such as Int8array, which processes the bytes into a signed 8-bit integer set, and Float32array the bytes into a 32-bit The collection of floating point numbers . These are called type arrays [2], which can force you to work on a particular number type, rather than containing any type of data (like a traditional array).

You can use Arraybuffer as a priority when working with binaries, which gives you more granular control over your data. To explain that all ins and outs about Arraybuffer are beyond the scope of this blog, you just need to know that you can easily read a file as a arraybuffer when you need it. You can directly pass a arraybuffer to a Xhr object's send () method, send the raw data to the server (you will read this data in the server request to rebuild the file), as long as your browser fully supports XMLHttpRequest level 2[3] (Most of the latest browsers, including IE10 and OPERA12, are supported).

JavaScript file processing: file read

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.