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.