Ajax使用PDO发送输入文件图像

时间:2015-02-03 15:29:43

标签: php jquery ajax pdo ajaxform

经过多次研究后,我似乎无法找到我的代码存在的问题而且我正在跳跃,任何人都可以帮助我。我的问题是,插入后我似乎无法show/GET图像:

我的表格

<form enctype="multipart/form-data" id="form" action="insert.php" method="post" name="changer">
Name <input type="text" name="name" placeholder="First name"/> </br>
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" name="submitbtn" type="submit">
</form>

我的ajax功能

$('#form').on('submit',(function(e) 
{
  e.preventDefault();
  $.ajax({
  url: 'insert.php',
  type: "POST",
  data:  new FormData(this),
  contentType: false,
  cache: false,
  processData:false,
  success: function()
  {
    alert ("ok");

  },
  error: function() 
  {
    alert ("error");
  }                  
 });
}));

我的insert.php

<?php

$pdo = new PDO("mysql:host=localhost;dbname=binary", "root", "pass");
if(!$pdo)
{
    die('Erro ao criar a conexão');
    echo "db error!";
}
else
{
   $statement = $pdo->prepare('INSERT INTO tbl_images (image,name) VALUES (:image,:name)');

   if (isset($_FILES['image'])) 
   { 
      echo "entrou no file";
      // Temporary file name stored on the server
      $tmpName  = $_FILES['image']['tmp_name'];  
      $name = $_POST['name'];

      // Read the file 
      $fp      = fopen($tmpName, 'r');
      $data = fread($fp, filesize($tmpName));
      $data = addslashes($data);
      fclose($fp);

      $statement->bindParam(':image', $data);
     $statement->bindParam(':name', $name);

   if($statement->execute())
   {
      echo "update";
   }
   else
   {  
      echo "no update";
   }          
  }
}
?>

在此之后,我去了phpadmin,我可以看到我写的名字,还有:[BLOB - 64 KiB]。

现在,在我的show.php文件中,我有:

<?php

$pdo = new PDO("mysql:host=localhost;dbname=binary", "root", "pass");
if(!$pdo)
{
   die('Erro ao criar a conexão');
}
else
{
    $verb = $_SERVER["REQUEST_METHOD"];

    if ($verb == "GET") 
    {
        header('Content-type: image/jpg');

        $statement = $pdo->query("SELECT * FROM tbl_images");
        $result = $statement->fetch(PDO::FETCH_ASSOC);
        $statement->execute();

        $img = $result['image'];

        echo $img;
    }
}
?>

0 个答案:

没有答案