Blogger Information
Blog 34
fans 0
comment 0
visits 21955
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
12月9日_文件操作 ——文件上传 - 九期线上班
只猫
Original
724 people have browsed it

文件上传

前端 index.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>文件上传</title>
  6. </head>
  7. <body>
  8. <h2>文件上传</h2>
  9. <form action="demo.php" method="post" enctype="multipart/form-data">
  10. <!-- 一定要设置name属性 对应$_FILES键值 -->
  11. <input type="file" name="my_file">
  12. <button>上传</button>
  13. </body>
  14. </html>

demo.php
  1. <?php
  2. //文件上传
  3. //参数配置
  4. $fileType = ['jpg','png','gif'];
  5. $fileSize = 3145728; //3M
  6. //上传文件夹
  7. $filePath = '/uploads/';
  8. //原始文件名
  9. $fileName = $_FILES['my_file']['name']; //系统定义的
  10. //临时文件名
  11. $tempFile = $_FILES['my_file']['tmp_name']; //系统定义的
  12. //错误判断
  13. $uploadError = $_FILES['my_file']['error'];
  14. if($uploadError > 0){
  15. switch ($uploadError) {
  16. case 1:
  17. case 2:die('上传文件过大');
  18. case 3:die('文件上传不完整');
  19. default:die('未知错误');
  20. }
  21. }
  22. //判断扩展名
  23. $extension = explode('.', $fileName)[1];
  24. if(!in_array($extension,$fileType)){
  25. die('不允许上传'.$extension.'文件');
  26. }
  27. //生成临时文件名不重复
  28. $fileName = date('YmdHis',time()).md5(mt_rand(1,99)).'.'.$extension;
  29. //文件上传
  30. //判断是否是post
  31. if(is_uploaded_file($tempFile)){
  32. if(move_uploaded_file($tempFile, __DIR__.$filePath.$fileName)){
  33. echo "上传成功";
  34. }else{
  35. die('上传失败');
  36. }
  37. }else{
  38. die('非法操作');
  39. }
  40. exit;



总结:文件上传的几个步骤 :创建上传到服务器的文件夹,获取文件的原始文件名,临时文件名,分离出扩展名,做文件类型判断、上传错误判断、判断提交方式、重命名文件防止重名。上传文件原来自己写过,又复习了一遍。

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:之前学过, 应该是基础, 记代码不如记流程, 最终形成肌肉记忆, 不加思考的就能写出来就成功了
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post