Javascript 上传前检查文件大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11514166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:06:26  来源:igfitidea点击:

Check file size before upload

phpjavascriptfile-uploadimage-uploadingfilesize

提问by cchap

I am using this javascript that I got from here, and it works perfectly for what I need it to.

我正在使用我从这里获得的这个 javascript,它非常适合我需要的东西。

var _validFileExtensions = [".jpg", ".jpeg"]; 

function File_Validator(theForm){
    var arrInputs = theForm.getElementsByTagName("input"); 
    for (var i = 0; i < arrInputs.length; i++) { 
    var oInput = arrInputs[i]; 
    if (oInput.type == "file") { 
        var sFileName = oInput.value; 
        var blnValid = false; 
            for (var j = 0; j < _validFileExtensions.length; j++) { 
                var sCurExtension = _validFileExtensions[j]; 
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) { 
                    blnValid = true; 
                    break; 
                    } 
                } 

                if (!blnValid) { 
                    alert("Invalid image file type!"); 
                    return false; 
                } 
        } 
    } 

return true; 
} 

Now, I was wondering if, in addition, I could check the file size and fail if the file is bigger than 500kb -> all before pressing the submit/upload button?

现在,我想知道,此外,如果文件大于 500kb,我是否可以检查文件大小并失败 -> 在按下提交/上传按钮之前全部?

EDIT

编辑

After looking into what PHPMyCoder suggested, I end up solving by using this javascript code:

在研究了 PHPMyCoder 的建议后,我最终使用以下 javascript 代码解决了问题:

<script language='JavaScript'>
function checkFileSize(inputFile) {
var max =  3 * 512 * 512; // 786MB

if (inputFile.files && inputFile.files[0].size > max) {
    alert("File too large."); // Do your thing to handle the error.
    inputFile.value = null; // Clear the field.
   }
}
</script>

This checks the file size, and alert the user before submitting the form.

这会检查文件大小,并在提交表单之前提醒用户。

回答by Bailey Parker

Client side Upload Canceling

客户端上传取消

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

在现代浏览器(FF >= 3.6、Chrome >= 19.0、Opera >= 12.0 和 Safari 上的 buggy)上,您可以使用HTML5 File API。当文件输入的值发生变化时,此 API 将允许您检查文件大小是否符合您的要求。当然, this 以及MAX_FILE_SIZE可以被篡改,因此请始终使用服务器端验证。

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

服务器端上传取消

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZEhas been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

在服务器端,不可能阻止从 PHP 发生的上传,因为一旦调用 PHP,上传就已经完成。如果您想节省带宽,您可以使用 ini 设置拒绝从服务器端上传upload_max_filesize。问题在于这适用于所有上传,因此您必须选择适用于所有上传的自由内容。的使用MAX_FILE_SIZE已在其他答案中讨论过。我建议阅读它的手册。要知道它以及其他任何客户端(包括 javascript 检查)都可以被篡改,因此您应该始终进行服务器端 (PHP) 验证。

PHP Validation

PHP验证

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILESarray to find out the upload size. (Docs on the contents of $_FILEScan be found below the MAX_FILE_SIZEdocs)

在服务器端,您应该验证文件是否在大小限制范围内(因为到目前为止,除了 INI 设置之外的所有内容都可能被篡改)。您可以使用该$_FILES数组来找出上传大小。(有关内容的文档$_FILES可以在MAX_FILE_SIZE文档下方找到)

upload.php

上传.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

回答by Firze

I created a jQuery version of PhpMyCoder's answer:

我创建了一个 jQuery 版本的 PhpMyCoder 的答案:

$('form').submit(function( e ) {    
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});

function get_extension(filename) {
    return filename.split('.').pop().toLowerCase();
}

回答by Hew Wolff

JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.

在浏览器中运行的 JavaScript 通常无法访问本地文件系统。那是在沙箱之外。所以我认为答案是否定的。