Liaoche JS Tutorial Note the file operation

Source: Internet
Author: User
Tags html form

In an HTML form, the only control that can upload a file is <input type="file"> .

Note : When a form is included <input type="file"> , the form enctype must be specified as multipart/form-data , and method must be specified as post , that the browser can correctly encode and multipart/form-data send the Form's data in a format.

For security reasons, The browser only allows users <input type="file"> to click to select Local files, and the assignment with JavaScript <input type="file"> value is not Effective. When the user chooses to upload a file, JavaScript does not get the true path of the File:

typically, uploaded files are handled by the background server, and JavaScript can check the file extension when it submits the form to prevent users from uploading files that are not in an invalid format:

var f = document.getElementById(‘test-file-upload‘);var filename = f.value; // ‘C:\fakepath\test.png‘if (!filename || !(filename.endsWith(‘.jpg‘) || filename.endsWith(‘.png‘) || filename.endsWith(‘.gif‘))) { alert(‘Can only upload image file.‘); return false;}
File API

Because JavaScript is very limited to the user to upload files, especially the inability to read the contents of the file, so many need to manipulate the files of the webpage has to use flash such as Third-party plug-in to Achieve.

With the popularity of HTML5, the new file API allows JavaScript to read the contents of the file and get more information about the Files.

The HTML5 file API provides File and FileReader two main objects that can be used to obtain and read file Information.

The following example shows how to read a user-selected picture file and preview the <div> image in One:

var fileInput = document.getElementById (' Test-image-file '), info = document.getElementById (' Test-file-info '), preview = document.getElementById (' Test-image-preview ');Listen for change event: Fileinput.addeventlistener (' Change ',function() {Clear background image: preview.style.backgroundImage =‘‘;Check whether the file is Selected:If (!fileinput.value) {info.innerhtml =' No file selection ';Return }Get the file reference:var file = fileinput.files[0];Get file Information: info.innerhtml =' file: ' + file.name +' <br> ' + ' <br> ' +  ' modify: ' + file.lastmodifieddate; if (file.type!==  ' image/jpeg ' && file.type!==  ' image/png ' && file.type!==  ' image/gif ') {alert (  is not a valid picture file! '); return;} //read file: var reader = new filereader (); Reader.onload = function (e) {var data = e.target.result; //' Data:image/jpeg;base64,/9j/4aaqsk ... (base64 encoded) ... ' preview.style.backgroundImage =  ' URL (' + data + //reads The file in Dataurl form: reader.readasdataurl (file);});        

The code above demonstrates how to read the contents of a file through the HTML5 files Api. The file read in the form of Dataurl is a string, similar to data:image/jpeg;base64,/9j/4AAQSk...(base64编码)... , commonly used to set the Image. If server-side processing is required, base64, character the character after the string to the server and decodes it with Base64 to get the binary contents of the original File.

Callback

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

You might ask, how do you handle multitasking with single-threaded mode execution of javascript?

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 is an asynchronous operation, we do not know when the operation ends in JavaScript code, so we need to set up a callback function first:

function(e) {    // 当文件读取完成后,自动调用此函数:};

When the file reads are complete, the JavaScript engine automatically calls the callback function we Set. When the callback function is executed, the file has been read, so we can safely get the contents of the file inside the callback Function.

Liaoche JS Tutorial Note the file operation

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.