检查文件大小在上传和停止上传超过文件大小限制与javascript

Checking file size during upload and stopping upload exceeding file size limit with javascript?

本文关键字:文件大小 javascript 检查      更新时间:2023-09-26

是否有方法使用javascript或jquery来检查文件上传的进度(即服务器已接收多少字节或kb),并在超过一定限制时切断上传,向用户显示警告/错误消息?谢谢你。

这个例子可能会对您有所帮助: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>

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