首页 > php代码 > PHP判断file框是否已选择文件(支持多文件)

PHP判断file框是否已选择文件(支持多文件)

本例子要告诉你几种处理办法,一是用js 或者是jquery遍历判断,另一种是传给php之后利用tmp_name值来判断,方法都简单下面我们一起来看看。

单个表单时

<form action="?" method="post" enctype='multipart/form-data'>
文件上传:<input type="file" name="file" id="file" />
<input type="submit" id="send" value="提交" />
</form>
<?php
//判断pic文件框是否已经选择文件
if (!empty($_FILES['file']['tmp_name'])) {
    echo '已选择文件';
}else {
    echo '请选择文件';
}
//PS:$_FILES后面的['tmp_name']一定不要忘写,它表示是一个临时的意思
?>

当然这个可以先用JS去判断一下,方法如下:

<script>
var send = document.getElementById("send");
send.onclick = function () {
    var file = document.getElementById("file").value;
    if (file.length < 1) {
        alert('请选择图片');
        return false;
    }
}
</script>

多文件上传时


表单中有多个<input type="file" name="uploadfile" contentEditable="false" style="width:80%">, 

提交表单时需要判断其中至少要有一个input已经选择好文件。

<input type="file" name="uploadfile" contentEditable="false" style="width:80%"><br> 
<input type="file" name="uploadfile" contentEditable="false" style="width:80%"><br> 
<input type="file" name="uploadfile" contentEditable="false" style="width:80%"><br> 
<input type="file" name="uploadfile" contentEditable="false" style="width:80%"><br> 
<input type="file" name="uploadfile" contentEditable="false" style="width:80%">

使用jQuery进行判断:

var fileFlag = false;
$("input[name='uploadfile']").each(function () {
    if ($(this).val() != "") {
        fileflag = true;
        return false;
    }
});
if (fileFlag) {
    alert("已有选择好文件的");
}

只要fileFlag为true,就可以退出each循环,不需要再对剩下的input进行判断。 

在each中使用return false退出循环,使用return true结束当前次循环,进行下一次循环。


永久链接:http://www.phprm.com/code/58151.html

转载随意!带上文章地址吧。

标签:文件上传

相关文章

发表留言