博客列表 >PHP中的文件上传

PHP中的文件上传

王娇
王娇原创
2020年05月15日 06:47:00740浏览

学习总结

  • 文件上传操作封装在类中利于使用和维护
  • 文件批量上传时前端的input中写multiple参数
  • 文件上传时前端form必须是POST方式上传,method="POST" enctype="multipart/form-data",而且表单发送前的编码方式必须是二进制编码。

1.单文件上传类 upFException.php

  1. <?php
  2. namespace compotents\conn
  3. {
  4. include 'upFException.php';
  5. class UploadFile
  6. {
  7. private $oriFileName;//原始文件名
  8. private $fileType;//文件类型
  9. private $error;//错误类型
  10. private $tmpFileName;//临时文件名
  11. private $fileSize;//已上传文件大小
  12. public function __construct($file)
  13. {
  14. $this->oriFileName = $file['name'];
  15. $this->fileType = $file['type'];
  16. $this->error = $file['error'];
  17. $this->tmpFileName = $file['tmp_name'];
  18. $this->fileSize = $file['size'];
  19. }
  20. public function checkSuccess($fileType):bool//检测文件是否上传成功
  21. {
  22. $error = $this->error;
  23. $type = strstr($this->fileType,'/',true);
  24. try {
  25. if ($error > UPLOAD_ERR_OK) :
  26. switch ($error) :
  27. case UPLOAD_ERR_INI_SIZE:
  28. throw new upFException('上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值', 1);
  29. break;
  30. case UPLOAD_ERR_FORM_SIZE:
  31. throw new upFException('上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值', 2);
  32. break;
  33. case UPLOAD_ERR_PARTIAL:
  34. throw new upFException('文件只有部分被上传', 3);
  35. break;
  36. case UPLOAD_ERR_NO_FILE:
  37. throw new upFException('没有文件被上传', 4);
  38. break;
  39. case UPLOAD_ERR_NO_TMP_DIR:
  40. throw new upFException('找不到临时文件夹', 6);
  41. break;
  42. case UPLOAD_ERR_CANT_WRITE:
  43. throw new upFException('文件写入失败', 7);
  44. break;
  45. default:
  46. throw new upFException('未知类型错误', 8);
  47. endswitch;
  48. endif;
  49. if ($type !== strtolower($fileType)):
  50. throw new upFException('文件类型错误', 9);
  51. endif;
  52. return true;
  53. }
  54. catch (upFException $e)
  55. {
  56. echo $e;
  57. return false;
  58. }
  59. }
  60. public function saveFile($destDir,$destFileName)
  61. {
  62. $tmp = $this->tmpFileName;
  63. $ori = $this->oriFileName;
  64. $dest = $destDir.$destFileName;
  65. if(is_uploaded_file($tmp))://判断是否是post方式上传的文件
  66. move_uploaded_file($tmp,$dest);
  67. endif;
  68. }
  69. }
  70. }
  71. ?>
  • 单文件上传前端处理部分代码
  1. case 'regist':
  2. if($_SERVER['REQUEST_METHOD']==='POST'):
  3. $name = trim($_POST['userName']);
  4. $nc = trim($_POST['userNc']);
  5. $pwd = md5(trim($_POST['pwd1']));
  6. $tpwd = trim($_POST['pwd1']);
  7. $rdate = date('Y-m-d');
  8. //使用用户名生成文件头像
  9. $fileName = strstr($name,'.',true).'.png';
  10. //生成一个文件上传的对象
  11. $file = new UploadFile($_FILES['userHeadImg']);
  12. //检测文件是否上传成功,参数是文件上传的类型限定
  13. if($file->checkSuccess('image')):
  14. //如果文件上传成功,则保存文件到服务器上
  15. $destDir = $_SERVER['DOCUMENT_ROOT']. '/php11/0511/images/headImg/';
  16. $file->saveFile($destDir,$fileName);
  17. else:
  18. exit('<script>alert("头像上传失败");location.href="register.php";</script>');
  19. endif;
  20. $data = ['name'=>"$name",'nc'=>"$nc",'password'=>"$pwd",'tpassword'=>"$tpwd",'regdate'=>"$rdate",'headimg'=>"$fileName"];
  21. //先判断一下用户名是否已经注册
  22. $where = "`name`='$name'";
  23. $res = $user->select($table,$where);
  24. if(count($res)):
  25. exit('<script>alert("邮箱已经注册过了,可直接登录");location.href="login.php";</script>');
  26. else:
  27. $rowCount = $user->insert($table,$data); //返回受影响的记录条数
  28. if($rowCount):
  29. exit('<script>alert("注册成功");location.href="login.php";</script>');
  30. else:
  31. exit('<script>alert("注册失败");location.href="register.php";</script>');
  32. endif;
  33. endif;
  34. else:
  35. die('请求类型错误!');
  36. endif;
  • 实现效果

2.文件批量上传类 UploadMulFile.php

  1. <?php
  2. namespace compotents\conn
  3. {
  4. include 'upFException.php';
  5. class UploadMulFile
  6. {
  7. private $oriFileName = [];//原始文件名
  8. private $fileType = [];//文件类型
  9. private $error = [];//错误类型
  10. private $tmpFileName = [];//临时文件名
  11. private $fileSize = [];//已上传文件大小
  12. public function __construct($file)
  13. {
  14. $this->oriFileName = $file['name'];
  15. $this->fileType = $file['type'];
  16. $this->error = $file['error'];
  17. $this->tmpFileName = $file['tmp_name'];
  18. $this->fileSize = $file['size'];
  19. }
  20. public function checkSuccess($fileType):bool//检测文件是否上传成功
  21. {
  22. $errors = $this->error;
  23. foreach($errors as $key => $error ):
  24. $type = strstr($this->fileType[$key],'/',true);
  25. $ori = $this->oriFileName[$key];
  26. try {
  27. if ($error > UPLOAD_ERR_OK) :
  28. switch ($error) :
  29. case UPLOAD_ERR_INI_SIZE:
  30. throw new upFException($ori.'上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值', 1);
  31. break;
  32. case UPLOAD_ERR_FORM_SIZE:
  33. throw new upFException($ori.'上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值', 2);
  34. break;
  35. case UPLOAD_ERR_PARTIAL:
  36. throw new upFException($ori.'文件只有部分被上传', 3);
  37. break;
  38. case UPLOAD_ERR_NO_FILE:
  39. throw new upFException($ori.'没有文件被上传', 4);
  40. break;
  41. case UPLOAD_ERR_NO_TMP_DIR:
  42. throw new upFException($ori.'找不到临时文件夹', 6);
  43. break;
  44. case UPLOAD_ERR_CANT_WRITE:
  45. throw new upFException($ori.'文件写入失败', 7);
  46. break;
  47. default:
  48. throw new upFException($ori.'未知类型错误', 8);
  49. endswitch;
  50. endif;
  51. if ($type !== strtolower($fileType)):
  52. throw new upFException($ori.'文件类型错误', 9);
  53. endif;
  54. }
  55. catch (upFException $e)
  56. {
  57. echo $e;
  58. return false;
  59. }
  60. endforeach;
  61. return true;//如果没有错误,返回true
  62. }
  63. public function saveFile($destDir):array
  64. {
  65. $tmps = $this->tmpFileName;
  66. $images = [];
  67. foreach($tmps as $key => $tmp):
  68. $tmp = $this->tmpFileName[$key];
  69. $ori = $this->oriFileName[$key];
  70. $images[$key] = $ori;
  71. $dest = $destDir.$ori;
  72. if(is_uploaded_file($tmp))://判断是否是post方式上传的文件
  73. move_uploaded_file($tmp,$dest);
  74. endif;
  75. endforeach;
  76. return $images;
  77. }
  78. }
  79. }
  80. ?>
  • 文件批量上传前端代码 showGoods.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <link rel="stylesheet" href="css/form.css">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <div class="showgoods">
  11. <?php
  12. require 'autoLoad.php';
  13. use compotents\conn\UploadMulFile;
  14. if(count($_FILES)):
  15. $file = new UploadMulFile($_FILES['goods']);
  16. if($file->checkSuccess('image')):
  17. //如果文件上传成功,则保存文件到服务器上
  18. $destDir = $_SERVER['DOCUMENT_ROOT']. '/php11/0511/images/goods/';
  19. $images = $file->saveFile($destDir,$fileName);
  20. endif;
  21. ?>
  22. <div style="display: flex;flex-flow: row wrap;justify-content: space-evenly;
  23. align-items: center;">
  24. <?php foreach($images as $image):?>
  25. <div
  26. style="width: 180px;height:150px; display:flex;justify-content:cetner;align-items: center;margin: 10px 10px;">
  27. <img src="images/goods/<?php echo $image ?>" alt=""></div>
  28. <?php endforeach; ?>
  29. </div>
  30. <?php
  31. else:
  32. ?>
  33. <form action="" method="POST" enctype="multipart/form-data">
  34. <div>
  35. <input type="file" name="goods[]" multiple>
  36. </div>
  37. <div><button type="submit">上传</button></div>
  38. </form>
  39. <?php
  40. endif;
  41. ?>
  42. </div>
  43. </body>
  44. </html>
  • 代码效果图

3.文件上传异常类 upFException.php

  1. <?
  2. namespace compotents\conn
  3. {
  4. use Exception;
  5. class upFException extends Exception
  6. {
  7. // 在异常子类中,可以访问并重写Exception中的四个属性,通过__toString()格式化异常输出信息
  8. public function __toString()
  9. {
  10. return <<< UPLOAD
  11. <style>
  12. table {border-collapse: collapse;border:1px solid black;text-align: center;}
  13. td {border:1px solid black;padding: 5px;}
  14. tr:first-of-type {background-color:#eee;
  15. }
  16. tr:last-of-type td {color: coral;}
  17. </style>
  18. <table>
  19. <tr><td>代码</td><td>信息</td><td>文件</td><td>行号</td></tr>
  20. <tr><td>$this->code</td><td>$this->message</td><td>$this->file</td><td>$this->line</td></tr>
  21. </table>
  22. UPLOAD;
  23. }
  24. }
  25. }
  26. ?>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议