Go JavaScript file Operations (2)-filereader

Source: Internet
Author: User

In the previous article, I introduced the JavaScript operations file, focusing on how to get the Files object. These objects contain the metadata of the files that can be obtained when uploading or dropping them into a browser. With the file, of course, the next step is to read the file.

FileReader

FileReaderThe function is simple: Read the data from the file and save it to the JS variable. This API is deliberately designed to XMLHttpRequest be the same as the data is read from the outside. The read process is asynchronous and does not cause the browser to block.

FileReaderYou can return formats for file data in several formats, and these formats are required to read the file. The following methods can be used to announce the completion of reads:

    • readAsText()– Returns the plain text format of the contents of the file
    • readAsBinaryString()– returns the binary format of the file contents (not recommended – recommended readAsArrayBuffer() )
    • readAsArrayBuffer()– Returns the format of the contents of the file ArrayBuffer (recommended for image files)
    • readAsDataURL()– Returns the data URL format of the file contents

These formats should initialize the send()方法前要初始化一个 same HTTP request as the XHR object before the file read operation. Again, you have to listen to the event before you start reading it load . The results read fromevent.target.result 获取。例如:

1234567891011 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 be read! Code " + event.target.error.code);};reader.readAsText(file);

The example above prints the file in plain text. The method is executed when the file reads successfully onload 方法否则执行 onerrorFileReaderthe instance can be directly from the event.target中取到而且推荐这么取而不是直接 using reader variable: The result Success property contains the contents of the file, and error contains information about the success and failure.

Read Data URIs

The steps to read the data URI are approximately the same. Data URIs (sometimes referred to as data URLs) is sometimes a good choice, for example, to directly display images from the hard disk, case reference:

1234567891011121314 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 be read! Code " + event.target.error.code);};reader.readAsDataURL(file);

The above example inserts the read picture into the page. Since the data URI contains the contents of the entire picture, it can be directly assigned to the SRC attribute of an Image object and then displayed. You can also draw images directly into the <canvas> elements:

123456789101112131415161718 var reader = new FileReader();reader.onload = function(event) {    var dataUri = event.target.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 could not be read! Code " + event.target.error.code);};reader.readAsDataURL(file);

The example above reads a picture resource into an Image object and then draws it into a canvas (aspect each 100).

Data URIs is typically used in this way and can be used with any type of file. The most extensive use is to read the file as a data URI and display it instantly on the page.

Read Arraybuffers

ArrayBufferFormat [1] was first proposed as part of WebGL. ArrayBufferindicates that the number of bytes of any size is stored in a certain number of bytes. In this way, the data is read from a particular view ArrayBuffer , such as a Int8Array, collection of 8-bit signed integers at the bottom, and Float32Array , for example, a collection of 32-bit floating-point numbers at the bottom. These harmonics are called typed arrays [2], which makes it easy to force you to use a certain number of bytes to store instead of an infinite number of bytes (that is, traditional arrays).

You might use a ArrayBuffer file that is primarily used to process binaries for finer-grained manipulation of data. Here we discuss the ArrayBuffer 的方方面面完全超出了的本文的范围,只要知道将文件读成 ArrayBuffer格式是非常简单的即可。你可随时将 ArrayBuffer way through the XHR object send() to the server side (and then rebuild the data on the backend), as long as your browser fully supports XMLHttpRequest level 2[3] (the latest version of each major browser supports including IE10 and opera 12).

Next stage Notice

通过FileReaderReading data from a file is straightforward. If you will use XMLHttpRequest那么很容易学会从文件中读取数据。下期你将会学到更多 FileReader related events and understand common mistakes.

Resources
    1. ArrayBuffer
    2. Typed Array Specification
    3. XMLHttpRequest Level 2

Original:

Http://www.iunbug.com/archives/2012/06/04/220.html

Refer to:

http://blog.csdn.net/zk437092645/article/details/8745647

Go JavaScript file Operations (2)-filereader

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.