无法使用php上传图片

时间:2015-02-23 13:55:19

标签: php html mysql

我正在尝试使用php上传图像;但似乎不起作用,我无法弄清楚原因。当我尝试只插入没有图像的文本时,它工作正常(我的意思是如果我从php部分删除图像上传的所有代码);所以我猜错误就在这部分,但我无法找到它。 这是我目前使用的上传代码。对此有任何帮助表示赞赏。

if (isset($_POST['add'])) {

$text = $_POST['text'];
$title = $_POST['title'];
$category = $_POST['category'];

$fileName = $_FILES['userfile']['userfile'];
$tmpName = $_FILES['userfile']['tmp_name'];

// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());

// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = "/img/" . $myFile;

    $result = move_uploaded_file($tmpName, $path);

    if (!$result) {
        echo "Error uploading image file <br />";
        var_dump($_FILES);
        exit;
    } else {
        $db = new mysqli("localhost", "user", "mypass", "mydb");

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s<br/>", mysqli_connect_error());
        }
        mysqli_set_charset($db, "UTF8");

        $query = "INSERT INTO posts (post_text, image_name, post_image, post_title, category) VALUES (?, ?, ?, ?, ?)";
        $conn = $db->prepare($query);
        if ($conn == TRUE) {
            $conn->bind_param("ssssi",$text, $myFile, $path, $title, $category);
            if (!$conn->execute()) {
                echo 'error insert';
            } else {

                header("Location: index.php");
                exit;
            }
        } else {
            die("Error preparing Statement");
        }
    }
} else {
   echo 'error';
}

这是上传的表格

<form method="post" action="postblog.php" enctype="multipart/form-data">
Title: <input type="text" name="title" id="title">
Category: <select name="category" id="category"> 
Desc :<br />
<textarea id="text" name="text" rows="15" cols="80" style="width: 80%"></textarea>
Image: <input type="file" name="userfile" />
<input type="submit" name="add" id="add" value="Добави">
</form>

错误来自此处:

  

if(!$ result){echo&#34;上传图片文件时出错&#34 ;; }

1 个答案:

答案 0 :(得分:1)

变化        $fileName = $_FILES['userfile']['userfile'];$fileName = $_FILES['userfile']['name'];