Wednesday, November 15, 2017
Check and get meta with HTML Multiple File Input in JavaScript and jQuery
Check and get meta with HTML Multiple File Input in JavaScript and jQuery
Normally, we would want to do some minimal checking on files the user wanted to upload before sending it over to server - to save bandwidth and also prevent potential malicious user actions.
While getting and clearing an HTML file input is easy with jQuerys $.val() method, jQuery does not support such action on <input multiple> html file fields.
However, JavaScript actually has native support for such actions.
First thing to note: we can get all file objects from an <input multiple> field in JavaScript with the .files attribute as an array.
It means we can count the number of objects in the array like this : field.files.length
They also provided a few handy attribute for us if we are to validate the files:
1. file.type (returns type, which can be image, video or application - the result depends only on the extension name of the file, JavaScript will not try to read the data of the file on the front end. This validation work should be done on the server end.)
2. file.name (return file name)
3. file.size (return size in bytes)
These attributes are all returned as strings, so we can easily get value from them using split method, say, to get the name or the extension of a file, we may use
var fileName = file.name.split(.)[0]
var fileExtension = file.name.split(.)[1] or var fileExtension = file.name.split(.).pop() // returns last object in array.
In the next posts, I will try to post my complete solution on handling and validating files uploaded using a HTML multiple file input.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment