【问题标题】:Upload an image to a folder and get its path name将图像上传到文件夹并获取其路径名
【发布时间】:2012-05-21 13:59:14
【问题描述】:

我有一个带有文件输入字段的表单:

<tr align="left">
    <td>Image :</td>
    <td align="left">
        <input type="file" name="ImageFile" size="18">
    </td>
</tr>

然后我在提交时处理这个图像文件:

$image_tmpname = $_FILES['ImageFile']['name'];
$imgdir = "blogImages/";
$imgname = $imgdir.$image_tmpname;

$blogs = new Blogs();

move_uploaded_file($_FILES['ImageFile']['tmp_name'], $imgname);
    $insert = $blogs->insertBlog($heading, $article, $date, $imgname);

我要保存图片的目录叫blogImages,和上面的目录是同一个目录。

您可能会注意到,在上面我调用了 insertBlog 类中的一个函数 Blogs'. Insert blog takes all the info and inputs the data to a mysql table. The code forinsertBlog` 是:

function insertBlog($heading, $article, $date, $imgname){
        $query = "INSERT INTO Blogs (BlogTitle, MainArticle, PostDate, Image) VALUES ('$heading', '$article', '$date', '$imgname')";        
        $oDatabase = new database;
        $connection = $oDatabase->Connect();
        if (!mysql_select_db($oDatabase->Name(), $connection))
            $oDatabase->ShowError("Blogs.insertBlog");

        if (!(@ mysql_query ($query, $connection)))
            $oDatabase->ShowError("Blogs.insertBlog");

        return (mysql_insert_id());
    }

当用户填写表单时,它会将除图像信息之外的所有其他信息正确存储在 MySQL 表中。此外,它不会将实际图像存储在blogImages 文件夹中。那么如何让这个脚本将图像上传到blogImages 文件夹并将其路径存储在 mysql 表中。目前它没有将图像存储在数据库中,只将值 blogImages/ 放在我的 MySQL 表的图像路径字段中。

【问题讨论】:

  • 你检查上传是否真的成功了吗? if ($_FILES['ImageFile']['error'] !== UPLOAD_ERR_OK) { die("Upload failed"); }.
  • 它没有上传,因为当我转到 blogImages 文件夹时实际上什么都没有
  • 所以要么它根本没有上传,要么你有权限/路径问题。您的代码假定每次都成功,这是一个坏主意。开始进行错误检查。如果失败,move_uploaded_file 将返回 false。如果上传失败,则上传有一个非零错误代码,等等......
  • 在我的代码中我应该把它放在哪里? if ($_FILES['ImageFile']['error'] !== UPLOAD_ERR_OK) { die("Upload failed"); }
  • 在您开始操作上传之前的某个位置。

标签: php mysql forms file-upload insert


【解决方案1】:

要传输文件,您必须在 HTML 中指定 multipart/form-data enctype

<form enctype="multipart/form-data" action="" method="POST">

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 2020-05-06
    • 2014-02-12
    • 1970-01-01
    • 2012-04-29
    • 2016-04-02
    • 2019-02-19
    • 2015-10-10
    • 1970-01-01
    相关资源
    最近更新 更多