首页 > 解决方案 > PHP:图像未保存在服务器文件夹和数据库中(作为 URL)

问题描述

目前,我创建了一个可以允许用户上传照片的 PHP 系统。现在,我得到了这个错误。

PHP 警告:move_uploaded_file(images/before_4.png):无法打开流:C:\inetpub\wwwroot\tgotworker_testing\pages\dashboard\engineer\view_task\update_photo_before.php 中没有这样的文件或目录,第 28 行 PHP 警告:move_uploaded_file (): 无法在第 28 行的 C:\inetpub\wwwroot\tgotworker_testing\pages\dashboard\engineer\view_task\update_photo_before.php 中将“C:\Windows\Temp\phpA952.tmp”移动到“images/before_4.png”

下面是我的代码。

<?php

    require_once '../../../../config/configPDO.php';

    $report_id = $_POST['report_id'];
    $last_insert_id = null;

    //Allowed file type
    $allowed_extensions = array("jpg","jpeg","png");

    //File extension
    $ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));

    //Check extension
    if(in_array($ext, $allowed_extensions)) {

        $defID = "before_" . $report_id;
        $imgPath = "images/$defID.png";
        $ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";

        $query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
        $sql = $conn->prepare($query);
        $sql->bindParam(':report_id', $report_id);
        $sql->execute();

        if ($sql){

            move_uploaded_file($_FILES['uploadFile']['tmp_name'], $imgPath); //line 28
            echo "<script>alert('Saved')</script>";
            header("Location: view_task.php?report_id=".$_POST['report_id']);

        }else{
            echo "Error!! Not Saved";
        }


    } else {
        echo "<script>alert('File not allowed')</script>";
        header("Location: view_task.php?report_id=".$_POST['report_id']);    

    }

?>

谁能帮我解决这个问题?

标签: phpmysql

解决方案


您在第 28 行使用 file_get_contents() :

move_uploaded_file(file_get_contents($_FILES['uploadFile']['name']),$imgPath);

但是函数 move_uploaded_file 不需要它的结果。你可以这样做:

move_uploaded_file($_FILES['uploadFile']['tmp_name'],$imgPath);

对于绝对路径的第二个问题:在 $imgPath 中,也许您应该改用它:

$imgPath="C:/inetpub/wwwroot/tgotworker_testing/android/images/$defID.png";

推荐阅读