将文件上传到目标文件夹时遇到问题

时间:2016-10-02 19:14:21

标签: php upload

我是PHP的新手并且还在学习它...今天我无法弄清楚为什么文件是从目标目录上传的 - $ target_dir ..我多次更改$ target_dir但是我总是得到相同的结果..代码对我来说很好..

有什么想法吗?

谢谢..

 function avatarUpload(){

    $target_dir = "../uploads/avatars/";
    $target_file = basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["avatar"])) 
    {

        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) 
        {
            //echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else  {
           // echo "File is not an image.";
            $uploadOk = 0;
        }

    }

    // Check if file already exists
    if (file_exists($target_file)) 
    {
        do
        {
            $rand = rand(100,10000);
            $target_file = $rand .= $target_file;
        } 
        while( file_exists($target_file) );
    }

    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 5000000000) 
    {
        //echo "Sorry, your file is too large.";
        $uploadOk = 0;

    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;

    } else {

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)== true) 
        {

           // echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
           return $target_file;

        } else 
        {
           // echo "Sorry, there was an error uploading your file.";

           return $target_file;

        }
    }


    return $target_file;
    }

1 个答案:

答案 0 :(得分:0)

您忘记将目标目录附加到文件名。

$target_file = $target_dir .basename($_FILES["fileToUpload"]["name"]);