PHP中向MySQL数据库上传文件失败?

使用PHP代码向MySQL数据库中上传文件时,数据库中无法接到任何内容,但是用控制台向数据库中上传相同文件时就可以上传到数据库里,上传的文件可以正常获取。

HTML文件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <form action="test.php" method="post" enctype="multipart/form-data" name="mainForm" id="mainForm">
            <input type="file" name="myfile" />
            <br>
            <input type="submit" name="submit" value="submit" />
        </form>
    </body>
</html>

PHP文件:

<?php
    header("content-type:text/html;character=utf-8");
    $fp = fopen($_FILES["myfile"]["tmp_name"],"rb");
    $buf = addslashes(fread($fp,$_FILES["myfile"]["size"]));
    $dbh = new PDO("mysql:host = localhost;port = 3306; dbname = test","root","");
    if($dbh->query("INSERT picture(picture) VALUES('$buf')"))
    echo "图片上传成功";
    else 
    echo "图片上传失败";
    $dbh = NULL;
?>

1个回答

图片上传数据库你得先吧图片转换成Base64 再入库,但是,没人这么操作啊,这样数据库根本吃不消

正确应该是上传好,返回上传到URL路径,然后把这个路径入库


<?php
if ((($_myfileS["myfile"]["type"] == "image/gif")
|| ($_myfileS["myfile"]["type"] == "image/jpeg")
|| ($_myfileS["myfile"]["type"] == "image/pjpeg"))
&& ($_myfileS["myfile"]["size"] < 20000))
  {
  if ($_myfileS["myfile"]["error"] > 0)
    {
    echo "Return Code: " . $_myfileS["myfile"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_myfileS["myfile"]["name"] . "<br />";
    echo "Type: " . $_myfileS["myfile"]["type"] . "<br />";
    echo "Size: " . ($_myfileS["myfile"]["size"] / 1024) . " Kb<br />";
    echo "Temp myfile: " . $_myfileS["myfile"]["tmp_name"] . "<br />";

    if (myfile_exists("upload/" . $_myfileS["myfile"]["name"]))
      {
      echo $_myfileS["myfile"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_myfile($_myfileS["myfile"]["tmp_name"],
      "upload/" . $_myfileS["myfile"]["name"]);
      echo "你可以把这个路径写入数据库: " . "upload/" . $_myfileS["myfile"]["name"];

      }
    }
  }
else
  {
  echo "Invalid myfile";
  }
?>
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐