1

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?

  • If in .NET - this is one of the best tools I've used http://krystalware.com/Products/SlickUpload/. Blocking extensions, detecting file size, progress bar.. simply briliant! – Marko Jul 06 '10 at 03:38

3 Answers3

4

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:

  1. Take whatever precautions on the server you can to limit the upload size (Each server technology handles it a bit differently). Always do this as client side controls can be bypassed
  2. Use a standard File Upload input element to start
  3. Progressively enhance it using something like the YUI Uploader or Uploadify. That way it works faster on files that do not match for users with Flash, but it also works for normal uploads since it will also be checked on the server.
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
2

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.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • Thanks meder, I can cache the file type and test it using regular Expressions (just a Thought), but I still need to cache the file size, which is impossible for now using JS, may be it might take some time to Implement in gathering all the attributes of a file using pure JS –  Jul 05 '10 at 17:08
  • 1
    Well, you can often determine file type by checking the file extension. That is possible using a little regexp on the filename. – Lèse majesté Jul 05 '10 at 17:15
1

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"! :)

Community
  • 1
  • 1
ANeves
  • 6,219
  • 3
  • 39
  • 63