Home  >  Article  >  Backend Development  >  HTML5 file upload example

HTML5 file upload example

WBOY
WBOYOriginal
2016-08-08 09:19:19923browse

Original address:

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

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

FileApi is one of the most interesting new features in HTML5. We can read the information about the displayed file before it is uploaded to the server, and can send the file without using a post form.

The following will show how to read the file information selected by the user and upload these files asynchronously using Ajax.


1. Display file information

1.1: When there is only one file

The HTML code is as follows

<input type="file" id="fileinput" />

When the user selects a file, the input element will generate a "change" event, so we can listen to this event:

document.getElementById('fileinput').addEventListener('change', function(){
    var file = this.files[0];
    // This code is 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 easy to use Simple, it adds the "files" attribute to the input element.

Summary: The "files" attribute is not writable and can only read its contents. You may have noticed that you can get it by using this.files[0] The first file that the user has selected.


1.2: Multiple files

Now we want to display all the file information selected by the user.

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 users to select multiple files to upload.

document.getElementById('fileinput').addEventListener('change', function(){
    for(var i = 0; i<this.files.length; i++){
        var file =  this.files[i];
        // This code is 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" tag to filter the file types that users can upload. For example, When you only want users to upload images, you only need to filter out the MIME type "image/*":

<input type="file" id="fileinput" multiple="multiple" accept="image/*" />

1.3 Preview files

We can both read file information and read files Content. For example, we can preview files before uploading.

Take the preview image as an example:

HTML code is as follows:




    
    Preview images
    


Upload images ...

<input type="file" id="fileinput" multiple="multiple" accept="image/*" />

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);

previewImage function will display the file 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 be an image";
    }

    var thumb = document.createElement("div");
    thumb.classList.add(&#39;thumbnail&#39;); // Add the class thumbnail to the created div

    var img = document.createElement("img");
    img.file = file;
    thumb.appendChild(img);
    gallery.appendChild(thumb);

    // 使用FileReader来显示图片内容
    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 file content asynchronously. Use new FileReader to instantiate the object, and then call the readAsUrl method to read The data of the file. The

onload method is called like an event after the file content is read, and then the file content will be assigned to the src attribute of the image element: aImg.src = e.target.result;


2. Upload files

We use XMLHttpRequest (Ajax) to upload files.

Every file selected by the user will create an HTTP request and send it to the server.

First, define a method containing XMLHttpRequest To upload files.

function uploadFile(file){
    var url = &#39;server/index.php&#39;;
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    xhr.open("POST", url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Every thing ok, file uploaded
            console.log(xhr.responseText); // handle response.
        }
    };
    fd.append("upload_file", file);
    xhr.send(fd);
}

This method will generate an ajax request (via post method) to the specified url, and send the file content in the "upload_file" request parameter. We can pass $_FILES['upload_file'] To get this parameter.

Now, we will use the uploadFile method to upload the selected file.

<input type="file" id="uploadfiles" multiple="multiple" />

Js is 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]); //上传文件
    }
}, false);

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

The above introduces the HTML5 file upload example, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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