php上传图片存入数据库示例分享

大部分人的图片上传都是保存一个路径到数据库,这样在插入时确实快,也符合web的特点,但是在删除时就很麻烦,需要找到文件并删除,该代码能够把代码直接存入数据库,删除时一并删除。请注意:这样的话数据库大小会激增,请酌情使用

表结构代码如下:

  1. CREATE TABLE `upload` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `type` varchar(20) NOT NULL,
  4. `data` mediumblob NOT NULL,
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

index.html 代码如下:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>
  5. Post-Image
  6. </title>
  7. </head>
  8. <body>
  9. <form action="post.php" method="post" enctype="multipart/form-data">
  10. <input type="file" name="file" />
  11. <input type="submit" value="OK"/>
  12. </form>
  13. </body>
  14. </html>

post.php 代码如下:

  1. <?php
  2. if ($_FILES["file"]["error"] > 0)
  3. {
  4. echo "Error: " . $_FILES["file"]["error"] . "<br />";
  5. }
  6. else
  7. {
  8. $type = $_FILES["file"]["type"];
  9. $size = $_FILES['file']['size'];
  10. $tmp=$_FILES["file"]["tmp_name"];
  11. $fp = fopen($tmp,'rb');
  12. $data = bin2hex(fread($fp,$size));
  13. $dsn='mysql:host=localhost;dbname=test';
  14. echo '<pre>';
  15. try{
  16. $pdo = new PDO($dsn,'root','root');
  17. $pdo->exec("INSERT INTO `upload`(`type`,`data`) values ('$type',0x$data)");
  18. $id = $pdo->lastInsertId();
  19. echo 'upload success!<a href="view.php?">View</a>';
  20. $pdo = null;
  21. }catch (PDOException $e){
  22. echo $e->getMessage();
  23. }
  24. echo '</pre>';
  25. fclose($fp);
  26. }

view.php 代码如下:

  1. <?php
  2. $id = $_GET['id'];
  3. if(is_numeric($id)){
  4. $dsn='mysql:host=localhost;dbname=test';
  5. try{
  6. $pdo = new PDO($dsn,'root','root');
  7. $rs = $pdo->query('select * from `upload` where `id`='.$id);
  8. $row = $rs->fetchAll();
  9. $data = $row[0];
  10. header("Content-Type:${data['type']}");
  11. echo $data['data'];
  12. $pdo = null;
  13. }catch (PDOException $e){
  14. echo $e->getMessage();
  15. }
  16. }else{
  17. exit();
  18. }