JavaScript file processing: File Reading and javascript file processing

Source: Internet
Author: User

JavaScript file processing: File Reading and javascript file processing

In my previous blog, I introduced how to use files in JavaScript, focusing on how to obtain File objects. Only when a user uploads a 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 data from these files.

FileReader type

A single task of the FileReader type is to read data from a file and store 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 operations are asynchronous and will not block the browser.

FileReader can create multiple formats to represent the file data, and the format returned when the file is read is required. Read operations are completed by calling any of the following methods:

  • ReadAsText ()-returns the object content in plain text format
  • ReadAsBinaryString ()-returns the file content in the format of an encrypted binary data string (this method has been deprecated, instead of readAsArrayBuffer)
  • ReadAsArrayBuffer ()-returns the file content in the form of ArrayBuffer (useful for binary data and image files)
  • ReadAsDataURL ()-returns the file content in the form of a Data URL

Just as the send method of the xhr object initiates an Http request, each of the above methods starts a file read. In this example, before you start reading, you can listen to the loadings. event.tar get. result always returns the read results. For example:

Var reader = new FileReader (); reader. onload = function (event) {var contents = event.tar get. result; console. log ("File contents:" + contents) ;}; reader. onerror = function (event) {console. error ("File cocould not be read! Code "+ event.tar get. error. code) ;}; reader. readAsText (file );

In this example, we simply read the file content and output the content in plain text to the console. When a file is successfully read, the onload operation is called. If the file cannot be read for some reason, the onerror operation is called. In the event handler, you can use event.tar get to obtain the FileReader instance, and it is recommended that you use this instead of using the reader variable directly. The result attribute contains the file content when reading is successful and the error message when reading fails.

Read data URI

You can use similar methods to read a file as a data URI. The data URI (sometimes called a Data URL) is an interesting option, for example, if you want to display image files read from a disk, you can use the following code:

Var reader = new FileReader (); reader. onload = function (event) {var dataUri = event.tar get. result, img = document. createElement ("img"); img. src = dataUri; document. body. appendChild (img) ;}; reader. onerror = function (event) {console. error ("File cocould not be read! Code "+ event.tar get. error. code) ;}; reader. readAsDataURL (file );

This Code simply inserts an image file read from the disk on the page. Because this data URI contains all the data of the image, it can be directly transmitted to the src attribute of the image and displayed on the page. You can load the image and draw it to a <canvas> alternately:

Var reader = new FileReader (); reader. onload = function (event) {var dataUri = event.tar get. result, context = document. getElementById ("mycanvas "). getContext ("2d"), img = new Image (); // wait until the image has been fully processed img. onload = function () {context. drawImage (img, 100,100) ;}; img. src = dataUri;}; reader. onerror = function (event) {console. error ("File cocould not be read! Code "+ event.tar get. error. code) ;}; reader. readAsDataURL (file );

This code loads the Image data to a new Image object and draws it to a canvas (both width and length are set to 100 ).

Data URI is generally used for this, but can be used on any type of files. The most common use of reading a file as a data URI is to quickly display the file content on a web page.

Read ArrayBuffers

The ArrayBuffer type [1] was initially introduced as part of WebGL. An Arraybuffer represents a limited number of bytes and can be used to store numbers of any size. Reading an ArrayBuffer data requires a specific view. For example, Int8Array processes the bytes into a signed 8-bit integer set, float32Array is a collection of 32-bit floating point numbers. These are called type arrays [2], which forces you to work on a specific numeric type, rather than containing any type of data (like a traditional array ).

When processing binary files, you can use ArrayBuffer first, so that you can have more fine-grained control over data. To explain that all ins and outs of ArrayBuffer are beyond the scope of this blog, you only need to know that you can easily read a file into an ArrayBuffer when you need it. You can directly transmit an ArrayBuffer to the send () method of an XHR object and send the original data to the server (you will read the data in the request of the server to recreate the file ), as long as your browser fully supports XMLHttpRequest Level 2 [3] (most of the latest browsers, including IE10 and Opera12 ).

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.