上传文件,添加到数据库并显示给用户

时间:2014-01-26 16:15:42

标签: php mysql

我一直在尝试上传文件,将其保存到数据库中,然后向用户显示他上传的文件。 这是图像文件的数据库。

Field    Type         NULL   DeFault
ID        int          NO
PIC       varchar(255) NO

以下是用于上传文件的 HTML

<form method="post" action="addMember.php" enctype="multipart/form-data">

            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 

            <input TYPE="submit" name="upload" value="Add Picture"/>
          </form>

这是后面的php文件: -

<?php
 include 'dbconnector.php';

//This is the directory where images will be saved
$target = "/img";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form

$pic=($_FILES['photo']['name']);


// Connects to your Database


//Writes the information to the database
$query="INSERT into testImage VALUES(NULL, '" . $pic . "')";
$result=mysql_query($query,$db) or die (mysql_error($db));
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>

问题是,文件未上传到 img 目录。 代码有什么问题?

另外,我应该如何将代码写入显示相同的文件给用户? 感谢。

P.S - 我从其中一个stackoverflow页面中提取代码并进行了编辑。


更新: - 我现在看到所有文件现已上传到根 / 目录中。图像文件类似于 img (我在代码中提到的目录名称),然后是上传的文件名。 为什么它不在/ img目录中。

2 个答案:

答案 0 :(得分:0)

我很确定你错过了目录和文件名之间的/。它应该是:

$target = $target .'/'. basename( $_FILES['photo']['name']);

答案 1 :(得分:0)

您在$target中缺少目录分隔符。回显变量时可以看到问题。

$target = $target . "/" . basename( $_FILES['photo']['name']);

用它来显示图片:

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

   //Tells you if its all ok
   echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
   // print the image
   echo '<img src="' . $target . '" alt="uploaded image" />';
}

编辑:

从数据库中获取图片:

// connect to database

$query = mysql_query('SELECT pic FROM testImage WHERE id = 1;',$db) or die (mysql_error($db));

$image = mysql_result($result, 0);
echo "<img src=\"/img/$image\" alt=\"uploaded image\" />";