This article mainly introduces the File Upload API in JavaScript and the usage of the file upload API. For more information, see, processing file uploads on webpages is always a very troublesome task. In the past, we were not able to upload images by dragging images, nor did we have complicated Ajax upload techniques. We seldom processed batch uploads of multiple files. We cannot obtain the information during the upload process, unless it is obtained from the server after the upload is complete. Sometimes the uploaded file is not suitable until the upload is complete!
Now, the HTML5 revolution, the birth of modern browsers, and the upgrade of JavaScript provide us with the ability to use the Javascript and input [type = file] elements to obtain information about the file upload process.
Next let's take a look at how these file upload APIs are used!
Access the list of files to be uploaded
To obtain the list of files to be uploaded in all input [type = file], you need to use the files attribute:
// Assuming 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 loop technique to perform loop operations on FileList:
for (var i = 0, fileCount = uploadInput.files.length; i < fileCount; i++) { console.log(files[i]);}
It is very important that FileList has a length attribute.
Obtain the information of 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, and file name:
{ lastModified: 1428005315000, lastModifiedDate: Thu Apr 02 2015 15:08:35 GMT-0500 (CDT), name: "profile.pdf", size: 135568, type: "application/pdf", webkitRelativePath: ""}
The most useful basic information for us is that we can verify it before uploading 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].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, beyond the permitted range, or the upload type is incorrect, you can stop the user from uploading and then give them the necessary prompt about the reason why the file cannot be uploaded successfully.
The above is a brief introduction to the file upload API, hoping to help you learn.