上传前检查文件大小 [英] Check file size before upload
问题描述
var 使用这个JavaScript,我从这里得到了,它完全适用于我所需要的。 _validFileExtensions = [.jpg,.jpeg];
函数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;
$ b if(!blnValid){
alert(Invalid image file type!);
返回false;
}
}
}
return true;
$ b现在,我想知道如果我还可以检查文件大小如果文件大于500kb,则会失败 - >在按下提交/上传按钮之前,所有文件都会失败?
$ b 编辑
在查看PHPMyCoder的建议之后,我最终通过使用这个javascript代码来解决:
< script language ='JavaScript' >
函数checkFileSize(inputFile){
var max = 3 * 512 * 512; // 786MB
if(inputFile.files&& inputFile.files [0] .size> max){
alert(File too large。); //做你的事情来处理错误。
inputFile.value = null; //清除字段
}
}
< / script>
这会检查文件大小,并在提交表单前提醒用户。
在现代浏览器(FF> = 3.6,Chrome> = 19.0,Opera> = 12.0,Safari上有bug),您可以使用 HTML5 File API 。当文件输入的值改变时,这个API将允许你检查文件大小是否在你的要求范围内。当然,这个以及 MAX_FILE_SIZE
都可以被篡改,所以一直使用服务器端的验证方式。
< form method =postenctype =multipart / form-dataaction =upload.php>
< input type =filename =fileid =file/>
< input type =submitname =submitvalue =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 bytes)
// Submit form
} else {
// Prevent default并显示错误
evt.preventDefault();
}
},false);
< / script>
服务器端上传取消
服务器端,不可能阻止从PHP发生上传,因为一旦调用了PHP,上传已经完成。如果您想节省带宽,可以使用ini设置拒绝服务器端的上传 upload_max_filesize
。这样做的麻烦是这适用于所有上传,所以你必须选择自由的东西,适用于所有的上传。在其他答案中已经讨论了使用 MAX_FILE_SIZE
。我建议阅读 <一>。要知道,它和其他客户端(包括javascript检查)一起可能会被篡改,因此您应该始终进行服务器端(PHP)验证。
PHP验证
在服务器端,您应该验证该文件是否在大小限制内(因为除了INI设置之外的所有内容都可能被篡改)。您可以使用 $ _ FILES
数组来找出上传大小。 (关于 $ _ FILES
内容的文档可以在 MAX_FILE_SIZE
docs )
upload.php
<?php
if(isset($ _ FILES ['file']){
if($ _ FILES ['file'] ['size']> 10485760){// 10 MB(size也是字节)
//文件太大
} else {
//文件大小限制
}
}
I am using this javascript that I got from here, and it works perfectly for what I need it to.
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?
EDIT
After looking into what PHPMyCoder suggested, I end up solving by using this javascript code:
<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. 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.
<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_SIZE
has 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 Validation
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 $_FILES
array to find out the upload size. (Docs on the contents of $_FILES
can be found below the MAX_FILE_SIZE
docs)
upload.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
}
}
这篇关于上传前检查文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!