How to validate file size before uploading? [dupli

2020-02-13 06:26发布

Possible Duplicate:
How can you determine the file size in JavaScript?

GMail has the option to check file size and alerting without letting the page posting back.

How can I implement this feature myself?

4条回答
我命由我不由天
2楼-- · 2020-02-13 06:54

Using HTML5, you can achieve this on the client side using JavaScript. This is jQuery but it works without as well of course: http://jsfiddle.net/pimvdb/S4mEv/2/. Note that it's not available in all browsers (yet).

$('#file').change(function() {
    alert(this.files[0].size + " bytes");
});

https://developer.mozilla.org/en/DOM/File

查看更多
叼着烟拽天下
3楼-- · 2020-02-13 06:57

You can do that file HTML5 JS File API

You can test run the below codes in my web IDE (but please use google chrome or FF): http://codesocialist.com/#/?s=bN

The below codes retrieve the filetype and filesize for you :)

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {

    // Great success! All the File APIs are supported.
    function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // files is a FileList of File objects. List some properties.
        var output = [];
        for (var i = 0, f; f = files[i]; i++) {
          output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', f.size, ' bytes </strong></li>');
        }

        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
    }

    // Bind Event Listener
    document.getElementById('files').addEventListener('change', handleFileSelect, false);

} else {
    alert('The File APIs are not fully supported in this browser.');
}
查看更多
倾城 Initia
4楼-- · 2020-02-13 07:13

Gmail uses a Flash application for this purpose. If you want to check file sizes, you need to do this from within such an environment; JavaScript alone has no mechanism to accomplish this.

查看更多
▲ chillily
5楼-- · 2020-02-13 07:15

You can use Uploadify, it's a jQuery plugin that uses flash for checking file size and has other neat functions. http://www.uploadify.com/documentation/options/sizelimit/

查看更多
登录 后发表回答