Home > Web Front-end > JS Tutorial > body text

JavaScript file processing part 2 - sample code sharing for file reading

黄舟
Release: 2017-03-13 16:49:41
Original
1068 people have browsed it

In my previous blog, I introduced how to use files in JavaScript, focusing specifically on how to obtain the File object. Only when the user uploads the file by uploading or dragging and dropping, 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, which is to read data from a file and store it in a JavaScriptvariable. Its API is intentionally designed to be the same as XMLHttpRequest, because they both load data from an external resource (outside the browser). Read operations are asynchronous so they don't clog the browser.

FileReader can create a variety of formats to represent file data, and the format returned when reading a file is required. Reading operations are completed by calling any of the following methods:

  • readAsText() – Returns the file content in plain text

  • readAsBinaryString() – Returns the file content in the form of encrypted binary dataString (This method is deprecated, please use readAsArrayBuffer() instead)

  • readAsArrayBuffer() – Use the form of ArrayBuffer to return the file content (useful for binary data such as image files)

  • readAsDataURL() – Use the form of data URL to return the file content

Just like the send method of the XHR object initiates an HTTP request, each of the above methods initiates a file reading. At this point, before starting to read, you must listen to the load event, event.target.result always returns the result of the read. 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 be read! Code " + event.target.error.code);
};

reader.readAsText(file);
Copy after login

In this example, we simply read the file content and output the content to the console as plain text. The onload operation is called when the file is successfully read, 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 it this way instead of using the reader variable directly. The result attribute contains the file content when the read is successful and the error message when the read fails.

Read data URI

You can use a similar method to read the file as a data URI. The data URI (sometimes also called the data URL) is an interesting option, for example, if you want to To display an image file read from disk, you can do so 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 be read! Code " + event.target.error.code);
};

reader.readAsDataURL(file);
Copy after login

This code simply inserts an image file read from disk on the page. Because this data URI contains all the data for the image, it can be passed directly to the image's src attribute and displayed on the page. You can alternately load the image and draw it to a

<canvas<a href="http://www.php.cn/code/7892.html" target="_blank">></a>:

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);
Copy after login
This code loads the image data into a new Image object and draw it onto a canvas (width and length are both specified as 100).

Data URIs are typically used for 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 file contents in a web page.

Reading ArrayBuffers

The ArrayBuffer type

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

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


The above is the detailed content of JavaScript file processing part 2 - sample code sharing for file reading. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template