在我的表单中我正在尝试使用php上传多个或单个文件。所以我的html表看起来像这样:
<tr>
<td width="142"><b>Docs</b>
<td width="142"><input type="file" name="files[]" id="project_docs1" class="docfile" /></td>
<td width="142"><input type="file" name="files[]" id="project_docs2" class="docfile" /></td>
<td width="142"><input type="file" name="files[]" id="project_docs3" class="docfile" /></td>
</td>
现在,当我只上传一个文件时,它会显示错误消息,如:无效格式,但它应该接受一个文件。它不需要上传所有3个文件。你能告诉我为什么它会显示这个名为无效格式的错误消息吗?如果上传所有3个文件,那么它工作正常。
当我按下上传按钮而没有上传任何文件时,它显示$noOfUpload
变量的值1。为什么?
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "project_docs"; // Upload directory
$error = array(); // load error message
$files_name = array(); // get uploaded file name
foreach ($_FILES['files']['name'] as $key => $name) {
$size = $_FILES['files']['size'][$key]. "<br>";
$noOfUpload = count($name);
if($noOfUpload <= 0){
$error[] = "Upload your document/s<br>";
}elseif(!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)){
$error[] = "invalid file formate : $name<br>";
}
//$name = md5(uniqid()) . '-' . htmlspecialchars_decode($name);
$files_name[] = "$name";
}
if(!empty($error)){
foreach ($error as $e) {
echo "<div class='error'>$e</div>";
}
}else{
foreach ($files_name as $fn) {
echo "$fn<br>";
}
}
你的帮助更值得欣赏。 :)
答案 0 :(得分:1)
试试这个
if (isset($_FILES))
{
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
for ($i = 0; $i < count($_FILES['files']['name']); $i++)
{
if (in_array(pathinfo($FILES['files']['name'][$i], PATHINFO_EXTENSION), $valid_formats))
{
$tmp_path = $_FILES['files']['tmp_name'][$i];
if ($tmp_path != "")
{
if (move_uploaded_file($tmp_path, $new_path))
{
//Handle other code here
}
else
{
$error[] = ""; //your error handling
}
}
else
{
$error[] = ""; //your error handling
}
}
else
{
$error[] = "invalid file formate : $name<br>";
}
}
}
答案 1 :(得分:0)
您的代码是针对整个数组运行的,或者是否为空白。首先,计算你的数组然后运行你的代码直到那个数。
答案 2 :(得分:0)
<tr>
<td width="142"><b>Docs</b>
<td width="142"><input type="file" name="files[]" id="project_docs1" class="docfile" /></td>
</tr>
PHP代码:
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "project_docs"; // Upload directory
$error = array(); // load error message
$files_name = array(); // get uploaded file name
foreach ($_FILES['files']['name'] as $key => $name) {
$size = $_FILES['files']['size'][$key]. "<br>";
$noOfUpload = count($name);
if($noOfUpload <= 0){
$error[] = "Upload your document/s<br>";
}elseif(!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)){
$error[] = "invalid file format : $name<br>";
}
//$name = md5(uniqid()) . '-' . htmlspecialchars_decode($name);
$files_name[] = "$name";
}
if(!empty($error)){
foreach ($error as $e) {
echo "<div class='error'>$e</div>";
}
}else{
foreach ($files_name as $fn) {
echo "$fn<br>";
}
}