JS Upload file Preview Simple example _javascript tips

Source: Internet
Author: User
Tags base64 file info

1. The FILE API

HTML5 provides file and FileReader two methods to read and read files.

2. Example

 

The file read in Dataurl is a string, similar to Data:image/jpeg;base64,/9j/4aaqsk ... (base64 code) ...,

Often used to set up images. If you need server-side processing, the string base64, the following word Fu Fa to the server and BASE64 decoding can get the original file binary content.

3. Explain

The above code also demonstrates one of the most important features of JavaScript is single-threaded execution mode. In JavaScript, the browser's JavaScript execution engine always executes in single-threaded mode when executing JavaScript code, that is, no JavaScript code can be executed with more than 1 threads at any one time.

You might ask, single-threaded mode executes JavaScript, how does multitasking work?

In JavaScript, multitasking is actually called asynchronously, such as the code above:

Reader.readasdataurl (file);

An asynchronous operation is initiated to read the contents of the file. Because it's an asynchronous operation, we don't know when the operation ends in JavaScript code, so we need to set a callback function first:

Reader.onload = function (e) {
  //When the file read is complete, this function is called automatically:
};

When the file is read, the JavaScript engine automatically invokes the callback function that we set. When the callback function is executed, the file is read, so we can safely get the contents of the file within the callback function.

The above JS upload file Preview Simple example is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.