Home > Article > Web Front-end > Detailed explanation of file upload API in JavaScript_javascript skills
For web programmers, handling file uploads on web pages is always a troublesome thing. In the past, we were not able to upload images by dragging and dropping, nor did we have complex Ajax upload technology, and we rarely handled batch uploads of multiple files. We also cannot obtain information during the upload process unless it is obtained from the server after the upload is completed. Sometimes, you find that the uploaded file is inappropriate after you finish uploading!
Today, the revolution of HTML5, the birth of modern browsers, and the upgrade of JavaScript have provided us with the ability to use Javascript and input[type=file] elements to obtain information about the uploading file process.
Let’s take a look at how to use these upload file APIs!
Access file list information to upload
If you want to get the list of files to be uploaded 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 old-fashioned looping techniques to loop over the FileList:
for (var i = 0, fileCount = uploadInput.files.length; i < fileCount; i++) { console.log(files[i]); }
A very important point, there is a length attribute in FileList.
Get information about a single uploaded file
Each file object in FileList stores a large amount of information about the file, including the file size, file MIME type, last modification time, file name, etc.:
{ lastModified: 1428005315000, lastModifiedDate: Thu Apr 02 2015 15:08:35 GMT-0500 (CDT), name: "profile.pdf", size: 135568, type: "application/pdf", webkitRelativePath: "" }
The biggest use of this basic information for us is that we can verify the files before uploading them. 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].size; 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 the size of the file uploaded by the user is too large, exceeds the allowed range, or the upload type is wrong, you can prevent the user from uploading, and then give them the necessary prompts as to why the upload cannot be successful.
The above is a brief introduction to the file upload API. I hope it will be helpful to everyone's learning.