开发者

Get the file Attributes (client side) using Javascript

In my application, I need to calculate the size of the file in client side (before uploading to server).

I want to restrict开发者_如何学Python 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?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜