简体   繁体   English

上传前检查文件大小

[英]Check file size before upload

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.这会检查文件大小,并在提交表单之前提醒用户。

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 .在现代浏览器(FF >= 3.6、Chrome >= 19.0、Opera >= 12.0 和 Safari 上的 buggy)上,您可以使用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.当文件输入的值发生变化时,此 API 将允许您检查文件大小是否符合您的要求。 Of course, this, as well as MAX_FILE_SIZE , can be tampered with so always use server side validation.当然,这以及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.在服务器端,不可能阻止从 PHP 发生的上传,因为一旦调用 PHP,上传就已经完成。 If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize .如果您想节省带宽,您可以使用 ini 设置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_SIZE has been discussed in other answers. MAX_FILE_SIZE的使用已在其他答案中讨论过。 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.要知道它以及其他任何客户端(包括 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).在服务器端,您应该验证文件是否在大小限制范围内(因为到目前为止,除了 INI 设置之外的所有内容都可能被篡改)。 You can use the $_FILES array to find out the upload size.您可以使用$_FILES数组来找出上传大小。 (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs ) (有关$_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
    }
}

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();
}

JavaScript running in a browser doesn't generally have access to the local file system.在浏览器中运行的 JavaScript 通常无法访问本地文件系统。 That's outside the sandbox.那是在沙箱之外。 So I think the answer is no.所以我认为答案是否定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM