上传期间检查文件大小并使用javascript停止上传超过文件大小限制?

时间:2013-03-01 19:10:51

标签: javascript jquery

有没有办法使用javascript或jquery来检查文件上传的进度(即服务器收到了多少字节或kb),如果超过某个限制则切断上传,向用户显示警告/错误信息?谢谢。

1 个答案:

答案 0 :(得分:1)

此示例可能会帮助您:http://js1.hotblocks.nl/tests/ajax/file-drag-drop.html

(它还包括拖放界面,但很容易被忽略。)

基本上归结为:

<input id=files type=file>

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    xhr.file = file; // not necessary if you create scopes like this
    xhr.addEventListener('progress', function(e) {
        var done = e.position || e.loaded, total = e.totalSize || e.total;
        console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
    }, false);
    if ( xhr.upload ) {
        xhr.upload.onprogress = function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
        };
    }
    xhr.onreadystatechange = function(e) {
        if ( 4 == this.readyState ) {
            console.log(['xhr upload complete', e]);
        }
    };
    xhr.open('post', url, true);
    xhr.send(file);
}, false);
</script>

在进度方法中,您获得了文件大小等。我希望这可以解决您的问题。 问候。