I have a form with file upload capabilities and I would like to be able to have some nice client side error reporting if the file the user is trying to upload is too big, is there a way to check against file size with jQuery, either purely on the client or somehow posting the file back to the server to check?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
This code:
Returns the file size for an form input.
On FF 3.6 and later this code should be:
I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything.
NOTES:
This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). The second ["0"] is now firstChild.
If you want to use jQuery's
validate
you can by creating this method:You would use it:
You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.
For the HTML below
try the following:
As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/
Old browsers support
Be aware that old browsers will return a
null
value for the previousthis.files
call, so accessingthis.files[0]
will raise an exception and you should check for File API support before using itYou can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.
If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.
I am posting my solution too, used for an ASP.NET
FileUpload
control. Perhaps someone will find it useful.