上传多张图片时出错

时间:2018-03-14 06:05:48

标签: php image file-upload image-uploading

我试图一次上传多张图片这是我到目前为止所得到的:     

if(isset($_POST['submit']))
{

        $file_name=$_FILES["image"]["name"];

            foreach($file_name as $files)
            {
                $target_path = "Sub_uploads/".$files;

                if(move_uploaded_file($files["image"]["tmp_name"],$target_path)) 
                {   

                    $target_path="Sub_uploads/".$files;

                    $sql   = "INSERT INTO product_images (image) VALUES ('$target_path')"; 
                    $query = mysql_query($sql); 
                }
            }
             echo "<script>alert('data inserted');document.location='Sub_CateGory_image.php'</script>";
}
?>

似乎错误发生在这一行:if(move_uploaded_file($files["image"]["tmp_name"],$target_path))

2 个答案:

答案 0 :(得分:1)

您需要使用ForEach $files

的变量
if(isset($_POST['submit']))
{

        $file_name=$_FILES;

            foreach($file_name as $files)
            {
                $target_path = "Sub_uploads/".$files["image"]["name"];

                if(move_uploaded_file($files["image"]["tmp_name"],$target_path)) 
                {   

                    $target_path="Sub_uploads/".$files["image"]["name"];

                    $sql   = "INSERT INTO product_images (image) VALUES ('$target_path')"; 
                    $query = mysql_query($sql); 
                }
            }
             echo "<script>alert('data inserted');document.location='Sub_CateGory_image.php'</script>";
}

答案 1 :(得分:0)

当您遍历name数组时,连接的tmp_name属性将具有与当前迭代name相同的键。因此,在key添加foreach并在此密钥下获得tmp_name

$file_name = $_FILES["image"]["name"];
foreach($file_name as $key => $files)   // add `$key` here
{
    $target_path = "Sub_uploads/".$files;
    // use `$key` to get connected `tmp_name`
    if(move_uploaded_file($_FILES["image"]["tmp_name"][$key], $target_path)) 
    {   
        $target_path="Sub_uploads/".$files;
        $sql   = "INSERT INTO product_images (image) VALUES ('$target_path')"; 
        $query = mysql_query($sql); 
    }
}