将图像上传到文件夹中

时间:2015-02-02 19:55:48

标签: php mysql file-upload

我正在尝试将多个文件上传到文件夹中,并将文件名保存到数据库中。我的代码无法将文件上传到文件夹中。

这是我的代码:

<?php
if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];  
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }       
        $query="INSERT into pictures (PictureName) VALUES('$file_name'); ";
        $desired_dir="user_data";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
            }else{                                  // rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
         mysql_query($query);           
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}
?>

<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple/>
    <input type="submit"/>
</form>

1 个答案:

答案 0 :(得分:0)

尝试使用for循环并将当前图像存储在数据库中并移动它

$image_array = $_FILES['files']['name'];
$tmp_array = $_FILES['files']['tmp_name'];
for ($move_files=0; $move_files < count($image_array); $move_files++) { 
        $image = "$desired_dir/".$image_array[$move_files];
        $tmp_image = $tmp_array[$move_files];
//do other stuff like checking if image exists
    code here
//
 $query="INSERT into pictures (PictureName) VALUES('$image'); ";
 $db-exec($query); 
        move_uploaded_file($tmp_image, $image);
     }