簡體   English   中英

在上傳過程中檢查文件大小並使用javascript停止上傳超過文件大小限制的文件?

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

有沒有一種方法可以使用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>

在進度方法中,您得到了文件大小等。我希望這可以解決您的問題。 問候。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM