创建图像上传选项的困难

时间:2015-10-19 14:55:05

标签: php arrays image file

我创建了一个测试页面,用于学习如何上传图像。我试图将图像保存到我创建的名为image的文件夹中,然后在我的数据库中存储该图像的文件名,以帮助处理空间。现在图像文件名不存储,而是存储单词Array。我确实得到了错误,以及其他错误。点击上传后,我收到以下错误:

  

警告:move_uploaded_file(image / picturetest.jpg):无法打开流:第34行/home4/fdfsfs/public_html/example.com/img_test.php中没有此类文件或目录< / p>      

警告:move_uploaded_file():无法移动&#39; / tmp / phpUg7p4D&#39;到&#39; image / picturetest.jpg&#39;在/home4/fdsfafa/public_html/example.com/img_test.php第34行

There was an error!
  

**注意:第59行/home4/fdsfaf/public_html/example.com/img_test.php中的数组到字符串转换

第34行是:

if (move_uploaded_file($tmp_name, $destinationFolder.$filename)) {

第59行是:

$stmt->execute();

完整脚本:

$filename = $_FILES['file']['name'];
//$filesize = $_FILES['file']['size'];
//$filetype = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];

if(isset($_POST['create'])){
    $file = $filename;
    $file = $_FILES['file'];
    //$file = "productpics/". $_FILES['file']['name']; // save the filename
}else {
    echo "error!";
    }

if (isset($filename )) {
    if (!empty($filename)) {

        $destinationFolder = 'image/';

        if (move_uploaded_file($tmp_name, $destinationFolder.$filename)) {
            echo 'Uploaded!';
        } else {
            echo 'There was an error!';
        }

    } else {
        echo 'Please choose a file.';
    }
}


//Connection
$con = mysqli_connect("localhost","","","");
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    if ($stmt = mysqli_prepare($con, "INSERT INTO image (img) VALUES (?)")) {

                    /* bind parameters for markers */
                    $stmt->bind_param('s', $file);

                    /* execute query */
                    $stmt->execute();
                    //if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);}

                /* close statement */
                mysqli_stmt_close($stmt);
                    echo "Success!";
                } else {
                    echo "Failed!";
                }

$result = mysqli_query($con,"SELECT * FROM image");
    if($row = mysqli_fetch_array($result)) {
        if($row['img'] == ""){
            echo "<img src='images/default_pic.png' alt='No Picture'>";
        } else {
            echo "<img src='images/".$row['img']."' alt='Profile Picture'>";
        }
            echo "<br><br><br><br>";
    }
?>


<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" class="inputbarfile">
    <input type="submit" name="create" id="signinButton" value="Upload">
</form>

有人看到我做错了吗???

2 个答案:

答案 0 :(得分:1)

因此,为了“重做”你所拥有的东西,我把它分解为部分(函数)。它基本相同,但是每个部分都被分解,因此1)更容易管理每个部分2)更容易排除故障3)更容易添加错误处理。

<?php
// If you make a file function, you can change where things are saved
// You can also change the destination (for portability)
function UploadFile($fileArray = array(), $destinationFolder = 'image/')
    {
        $filename       =   $fileArray['file']['name'];
        $tmp_name       =   $fileArray['file']['tmp_name'];
        $filesize       =   $fileArray['file']['size'];
        $file_error     =   $fileArray['file']['error'];
        $file           =   $fileArray['file'];
        // Save all the default data.
        // Success and error should be set by default to fail
        $return['error']        =   true;
        $return['success']      =   false;
        $return['file']['dest'] =   $destinationFolder.$filename;
        $return['file']['size'] =   $filesize;

        if($file_error == 0)
            $return['error']    =   false;
        // I added a directory creation function so you don't have to 
        // manually make folders. This will do it for you.
        if(!is_dir($destinationFolder))
            mkdir($destinationFolder,0755,true);
        // If your filename is not empty, return success or fail of upload
        if (!empty($filename))
            $return['success']  =   (move_uploaded_file($tmp_name, $destinationFolder.$filename));  

        return $return; 
    }

// Create a function that quickly returns your connection   
function Connection()
    {
        //Connection
        $con = mysqli_connect("localhost","","","");
            if (mysqli_connect_errno()) {
                printf("Connect failed: %s\n", mysqli_connect_error());
                exit();
            }

        return $con;
    }

// Create a save-to-database function so it's easier and reusable
function SaveToDb($con,$filename = false)
    {
        // Return fail immediately if the connection is false
        // or the image name is invalid
        if(empty($filename) || !$con)
            return false;

        if ($stmt = mysqli_prepare($con, "INSERT INTO image (img) VALUES (?)")) {
                $stmt->bind_param('s', $filename);
                $stmt->execute();
                mysqli_stmt_close($stmt);

                return true;
            }

        return false;
    }

// This just gets the image from the destination column. Not the most
// efficient, but you can change it to fetch by id or whatever is unique
function getPhoto($con,$dest)
    {
        $result = mysqli_query($con,"SELECT * FROM `image` where `img` = '$dest'");
        if($row = mysqli_fetch_array($result))
            return $row;

        return 0;
    }

使用:

// Make sure all functions above are include here

// Get the database connection
$con        =   Connection();
// Check for post   
if(isset($_POST['create'])) {
        // Try uploading
        $upload =   UploadFile($_FILES);
        // If upload fails
        if(!$upload['success'])
            echo '<h3>Sorry, an error occurred</h3>';
        else {
                // You could add error handling here based on the results of 
                // each function's success or failure below.

                // Try to save it
                $saveToDb   =   SaveToDb($con,$upload['file']['dest']);
                // Get the profile from image name
                $profPic    =   ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false; ?>

                <img src="<?php echo (!empty($profPic) && $profPic != 0)? $profPic['img'] : "default_pic.png"; ?>" alt="<?php echo (!empty($profPic) && $profPic != 0)? "Profile Picture" : "No Picture"; ?>" />
                <?php
            }
    }
?>

答案 1 :(得分:0)

你需要将数组转换成字符串,检查出来......

http://www.w3schools.com/php/func_string_implode.asp