: This article mainly introduces examples of uploading HTML5 files. For more information about PHP tutorials, see. Original article 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 one of the most interesting new functions of HTML5. we can read the information of the displayed file before the file is uploaded to the server, and can send the file without using the post form.
The following describes how to read user-selected file information and upload these files asynchronously using Ajax.
1. display file information
1.1: only one file
The HTML code is as follows:
When you select a file, the inpupt 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 simple to use. It adds the "files" attribute to the input element.
Summary: The "files" attribute cannot be written. you can only read the content. you may have noticed that you can use this. files [0] to obtain the first file you have selected.
1.2: multiple files
Now we want to display all the selected files.
The HTML code is as follows:
You only need to add the "multiple" attribute to the input element, so that you can select multiple files to upload.
Document. getElementById ('fileinput'). addEventListener ('change', function () {for (var I = 0; I
Summary: You can also add the "accept" label to filter the file types that users can upload. for example, if you only want users to upload images, you only need to filter out the MIME type "image:
1.3 preview a file
We can read both the file information and the file content. for example, we can preview the file before uploading.
For example, preview an image:
The HTML code is as follows:
Preview images Upload images...