【问题标题】:Difficulties creating image upload option创建图像上传选项的困难
【发布时间】:2016-01-17 23:45:26
【问题描述】:

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

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

警告:move_uploaded_file(): 无法在线将 /home4/fdsfafa/public_html/example.com/img_test.php 中的 '/tmp/phpUg7p4D' 移动到 'image/picturetest.jpg' 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>

有没有人看到我做错了什么???

【问题讨论】:

  • 您可能希望将其保存到您的数据库中:$destinationFolder.$filename
  • 至于第一个警告,你确定你把图片存储的文件夹放在了正确的地方吗?尝试使用mkdir() 创建文件夹
  • 在顶部,您将$file = $_FILES['file']; 分配给$_FILES['file'] 数组给变量$file。在底部,您尝试将该数组写入数据库而不处理数组,因此它会写入Array
  • 警告是针对找到的目录或文件,因此它可能试图保存到与您预期不同的位置的文件夹中
  • 嗯,您可能正在尝试存储最终目的地,即:$destinationFolder.$filename。把它放到你的数据库中

标签: php arrays image file


【解决方案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
            }
    }
?>

【讨论】:

  • 首先,非常感谢您提供如此详细的扩展!好的,所以这显然消除了我收到的消息。这绝对超出了我的技能水平,所以我试图将其全部投入。每当我上传照片时,它会在页面上以非常大的版本显示图像,所以它的真实尺寸。有没有办法让图像只出现在“你的图像”框中?如果你愿意,你可以在我的网站上看到它在做什么。我现在只是在玩这个,所以如果有帮助,请随时上传图片。 realtorcatch.com/test_test_img
  • 是的,您可以使用 CSS 使其以正确的大小出现在某个图像框中 -> max-width 和/或 max-height 要使其出现在您想要的框中,您只需更改逻辑并将&lt;img src="&lt;?php echo (!empty($profPic) &amp;&amp; $profPic != 0)? $profPic['img'] : "default_pic.png"; ?&gt;" alt="&lt;?php echo (!empty($profPic) &amp;&amp; $profPic != 0)? "Profile Picture" : "No Picture"; ?&gt;" /&gt;放在if之外
  • 理想情况下,您希望将用户信息保存到会话中以填充该字段。
  • 我的更改是否正确?要将用户的信息保存到会话中,我是否只保存图片,以便显示他们当前的图片?
  • 您要做的是,当用户登录时,您会将用户 ID、用户名,也许还有其他几个变量保存到会话中,然后在将用户图像保存到磁盘时,保存对他们的引用在与他们的图像相对应的数据库中。然后,当他们转到他们的个人资料时,您可以将其拉出。
【解决方案2】:

你需要把数组转成字符串,看看这个……

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

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
猜你喜欢
  • 2021-01-15
  • 1970-01-01
  • 2018-06-16
  • 2023-01-09
  • 1970-01-01
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多