我正在使用多图片上传社交网络应用。我正在为每个上传的文件分配$_session['file_id']
作为数组索引(文件ID来自db)。但我只希望用户每个帖子最多上传4张图片。所以我在上传之前计算images.length
,如果是== 4
,则警告用户他无法同时上传更多文件,否则会发生正常上传。出于安全考虑,我有一个unset($_session['file_id'])
用于确保4个文件不会上传错误,或者用户更改javascript(每次上传时for
循环),以计算$_session['file_id'])
。
我遇到的问题是js本身不应该确保文件没有上传4次,我想ajax upload保留在队列中,并在上传第4个文件之前检查文件号。有没有其他方法我可以直接在PHP上使用,记住我不能为普通用户取消设置文件(4个文件已经上传并等待发送按钮),但我需要加上取消设置文件如果用户reflesh,或退出页面?谢谢你的时间。
的JavaScript
var checkfilecount = 0;
$('#file').change(function() {
checkfilecount++;
checkfile = $("#images).length;
if (checkfile < 4 && checkfilecount < 4) {
$("#filesend").submit();
}
else {
setTimeout(function(){
alert("Sorry, You can`t upload too many files at once")
},3000)
}
})
和#postsend:
checkfilecount = 0;
PHP
if (isset($_SESSION['files_id'])) {
$counting = 0;
foreach($_SESSION['files_id'] as $key => $val)
{
$counting++;
if ($counting == 4) {
unset($_SESSION['files_id']);
exit("error on session array");
}
}
}
答案 0 :(得分:1)
为<input>
分配随机类名,例如:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" class="fileuploadCounter">
<input type="file" name="file[]" class="fileuploadCounter">
<input type="file" name="file[]" class="fileuploadCounter">
<input type="file" name="file[]" class="fileuploadCounter">
</form>
初始化后,$('.fileuploadCounter').length()
将返回该类的元素数量,在本例中为4。请参阅jQuery documentation。
<小时/>
下的旧答案
将<input>
代码上的名称更改为images[]
,并计算$_POST['images']
服务器端。
例如:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(isset($_FILES['file'])){
// Because we added [] in the name tag and they match names, $_FILES['file'] is now an array containing the images.
if(count($_FILES['file']) > 4){
// More than 4 files
}
else
{
// Less then four!
foreach($_FILES['file'] as $file){
move_uploaded_file($file["file"]["tmp_name"], "uploads/" . $files["file"]["name"]);
}
}
}
}
?>