For web programmers, it's always a hassle to process file uploads on a Web page. In the past, we can not drag and drop upload pictures, there is no complex Ajax upload technology, rarely deal with multiple file bulk uploads. We also can't get the information in the upload process, unless we get it from the server after the upload is complete. Sometimes, when you upload finished, you will find that the uploaded file is not suitable!
Today, the HTML5 Revolution, the birth of modern browsers, and the upgrading of JavaScript, provide us with the ability to use JavaScript and input[type=file elements to gain information about uploading file processes.
Let's take a look at how these upload file APIs are used!
Access the file list information to upload
If you want to get a list of files to upload in all input[type=file, you need to use the files attribute:
Assuming <input type= "file" id= "upload" multiple>
var uploadinput = document.getElementById (' upload ');
Uploadinput.addeventlistener (' Change ', function () {
console.log (uploadinput.files)//File listing!
});
Unfortunately, this filelist does not have a method called foreach, so we can only use the old-fashioned looping technique to loop through the filelist:
for (var i = 0, FileCount = uploadInput.files.length i < FileCount; i++) {
console.log (files[i));
It is important to note that there is a length attribute in the filelist.
Get information for a single uploaded file
Each file object in FileList contains a large amount of information about the file, including the size of the file, the MIME type of the file, the last modification time, the file name, and so on:
{
lastmodified:1428005315000,
lastmodifieddate:thu APR 2015 15:08:35 GMT-0500 (CDT),
name: " Profile.pdf ",
size:135568,
type:" Application/pdf ",
webkitrelativepath:" "
}
The most useful thing about these basic information is that we can check them before uploading the files. For example, you can verify the file type and size:
var maxallowedsize = 500000;
for (var i = 0, FileCount = uploadInput.files.length, totalsize = 0; i < FileCount; i++) {
totalsize = Files[i].s ize;
if (TotalSize > Maxallowedsize) {
//Notify the user that their file (s) are too large
}
if (files[i].type != ' Application/pdf ') {
//Notify of invalid file type for file in question
}
}
If a user uploads a file that is too large, exceeds the allowable range, or uploads the wrong type, you can block the user from uploading, and then give them the necessary hints as to why it cannot be uploaded successfully.
The above is the file upload API to do a brief introduction, I hope to help you learn.