HTML5 File Upload Example

Source: Internet
Author: User

Original address:

http://www.webcodegeeks.com/html5/html5-file-upload-example/

This article will show you how to use HTML5 to read user-selected file information and upload the file to a server.

Fileapi is the most interesting of the newly added features of HTML5. We can read the information of the display file before uploading it to the server, and can send the file without using the Post form.

The following shows how to read the file information selected by the user and use Ajax to upload the files asynchronously.


1. displaying file information

1.1: Case with only one file

The HTML code is as follows

<input type= "File" id= "Fileinput"/>

When a user chooses a file, the Inpupt element generates a "change" event, so we can listen to the event:

document.getElementById (' Fileinput '). AddEventListener (' Change ', function () {    var file = this.files[0];    This code was only for demo ...    Console.log ("Name:" + file.name);    Console.log ("Size:" + file.size);    Console.log ("type:" + file.type);    Console.log ("Date:" + file.lastmodified);}, False);

As you can see, Fileapi is very simple to use, and it adds the "files" attribute to the INPUT element.

Summary: The files property is not writable and can only read the contents. You may have noticed that using this.files[0] will get the first file that the user has selected.


1.2: Multiple Files

Now we want to display all the file information that the user chooses.

The HTML code is as follows

<input type= "File" id= "Fileinput" multiple= "multiple"/>

We only need to add the "multiple" attribute to the INPUT element, which allows the user to select multiple file uploads.

document.getElementById (' Fileinput '). AddEventListener (' Change ', function () {for    (var i = 0; i< This.files.length; i++) {        var file =  This.files[i];        This code was only for demo ...        Console.group ("File" +i);        Console.log ("Name:" + file.name);        Console.log ("Size:" + file.size);        Console.log ("type:" + file.type);        Console.log ("Date:" + file.lastmodified);        Console.groupend ();    }}, False);

Summary: You can also add the "Accept" tab to filter the types of files that users can upload. For example, when you only want users to upload a picture, you only need to filter out the MIME type "image/*":

<input type= "File" id= "Fileinput" multiple= "multiple" accept= "image/*"/>

1.3 Previewing files

We can read both the file information and the contents of the file. For example, we can preview a file before uploading it.

To preview a picture example:

The HTML code is as follows:

<!doctype html>

Use JavaScript to manage file uploads.

Gallery.js

var uploadfiles = document.queryselector (' #fileinput '); Uploadfiles.addeventlistener (' Change ', function () {    var Files = this.files;    for (var i=0; i<files.length; i++) {        previewimage (this.files[i]);}    }, False);

The Previewimage function will display the files selected by the user.

Gallery.js

function Previewimage (file) {    var Galleryid = "Gallery";    var gallery = document.getElementById (Galleryid);    var imageType =/image.*/;    if (!file.type.match (ImageType)) {        Throw "file type must is an image";    }    var thumb = document.createelement ("div");    Thumb.classList.add (' thumbnail '); Add the class thumbnail to the created div    var img = document.createelement ("img");    Img.file = file;    Thumb.appendchild (IMG);    Gallery.appendchild (thumb);    Use FileReader to display picture contents    var reader = new FileReader ();    Reader.onload = (function (aimg) {return function (e) {aimg.src = E.target.result;};}) (IMG);    Reader.readasdataurl (file);}

We introduced the FileReader object to read the contents of the file asynchronously. Use the new FileReader to instantiate the object, and then call the Readasurl method to read the file's data.

The OnLoad method is called as an event after the end of the file's content reading, and the contents of the file are assigned to the SRC attribute of the image element: Aimg.src = E.target.result;


2. Uploading Files

We use XMLHttpRequest (Ajax) to upload files.

Each user-selected file creates an HTTP request to be sent to the server.

First, define a method that contains XMLHttpRequest to upload the file.

function UploadFile (file) {    var url = ' server/index.php ';    var xhr = new XMLHttpRequest ();    var fd = new FormData ();    Xhr.open ("POST", url, true);    Xhr.onreadystatechange = function () {        if (xhr.readystate = = 4 && Xhr.status = =) {            //every thing OK, File uploaded            Console.log (xhr.responsetext);//Handle response.        }}    ;    Fd.append ("Upload_file", file);    Xhr.send (FD);}

This method generates an AJAX request (via post) to the specified URL and sends the contents of the file in the "Upload_file" request parameter. We can get this parameter by $_files[' Upload_file ').

Now, we'll use the UploadFile method to upload the selected file.

<input type= "File" id= "Uploadfiles" multiple= "multiple"/>

JS as follows:

var uploadfiles = document.queryselector (' #uploadfiles '); Uploadfiles.addeventlistener (' Change ', function () {    var files = this.files;    for (var i=0; i<files.length; i++) {        uploadfile (this.files[i]);//Upload file    }}, False);

The PHP script is as follows:

if (Isset ($_files[' upload_file '))) {    if (move_uploaded_file ($_files[' upload_file '] [' tmp_name '], "datas/". $_ files[' upload_file ' [' name ']) {        echo $_files[' upload_file ' [' Name ']. "OK";    } else {        echo $_files[' upload_file ' [' Name ']. "KO";    }    Exit;} else {    echo "No files uploaded ...";}


3. Download

All source code

HTML5 File Upload Example

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.