Reputation:
In my application, I need to calculate the size of the file in client side (before uploading to server).
I want to restrict the file being uploaded if it doesn't satisfy my requirements like file size, file type..
Is it possible to achieve this in client side using JavaScript?
Upvotes: 1
Views: 2511
Reputation: 6365
In browsers with support for HTML5´s File API, you now can.
This is true for updated browsers, not surprisingly IE excluded.
var files = $(this).attr('files');
var MAXFILESIZE = 500000; // bytes
if (files) {
// <input type="file" multiple>
for (var i = 0; i < files.length; i++) {
// We can also validate files[i].type or files[i].name vs an expected file type
if (files[i].size > MAXFILESIZE) {
alert('File "'+files[i].name+'" is too big.');
}
}
}
The future says "hello"! :)
Upvotes: 1
Reputation: 66191
In the vast majority of current browsers, there is no way to accomplish this with pure JS. Some of the newer HTML5 file tools may allow for this, but their support is limited.
You will need to go with a Flash based uploader tool to get this data before upload. Check out YUI Uploader to get you started.
I would suggest you implement it this way:
Upvotes: 4
Reputation: 186562
This isn't practically possible ( maybe it is with some Java+ActiveX exploit in IE ) before actually submitting the file with a POST request to the server.
Upvotes: 2