原生PHP实现单图、多图文件批量上传

原创 阁主  2023-08-27 17:43:44  阅读 2576 次 评论 0 条
摘要:

本文为PHP实现单图、多图文件上传,其余文件类型原理差不多,可自行修改代码。

介绍

简单的记录下如何处理解决使用PHP处理前端上传的多图处理功能,本文只贴了图片处理的方法,其余文件类型也是差不多的。各位道友可自行修改处理代码,都是八九不离十。文末也放了代码,可自行下载学习。

代码部分

html代码部分,input的name属性my_file后面加了一个中括号[],就是以数组形式上传,后端PHP接收到的数据就更好的以数组形式接收处理。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>图片上传</title>
  8. </head>
  9. <body>
  10. <form action="upload.php" method="post" enctype="multipart/form-data">
  11. <p> <input type="file" name="my_file[]" multiple></p>
  12. <button>提交</button>
  13. </p>
  14. </form>
  15. </body>
  16. </html>

PHP后端代码部分,可以根据自己的项目需求适当修改,这边只作保存image类型的图片文件描述。

  1. <?php
  2. printf('<pre>%s</pre>', print_r($_FILES, true));
  3. $res = upload($_FILES);
  4. printf('<pre>%s</pre>', print_r($res, true));
  5. // 单
  6. // print_r(uploadFile($_FILES));
  7. // 多
  8. print_r(uploadFile($res));
  9. function uploadFile(array $files, $uploadPath = 'uploads/storage'): array
  10. {
  11. if (!file_exists($uploadPath)) {
  12. mkdir($uploadPath, 0777, true);
  13. }
  14. foreach ($files as $file) {
  15. if ($file['error'] == 0) {
  16. // echo strstr($file['type'], '/', true);
  17. if (strstr($file['type'], '/', true) !== 'image') {
  18. $tips = $file['name'] . '文件类型错误';
  19. continue;
  20. } else {
  21. // 确保文件名的唯一性
  22. $targetName = $uploadPath . '/' . date('YmdHis') . md5($file['name'] . time()) . strstr($file['name'], '.');
  23. // echo $targetName;
  24. // 将文件从临时位置 移动到指定位置
  25. if (!move_uploaded_file($file['tmp_name'], $targetName)) {
  26. $tips = $file['name'] . '文件移动失败';
  27. continue;
  28. } else {
  29. $img[] = $targetName;
  30. }
  31. }
  32. }
  33. }
  34. if (!empty($tips)) {
  35. $res['error'] = $tips;
  36. } else {
  37. $res['fileRealPath'] = $img;
  38. }
  39. return $res;
  40. }
  41. // 处理多文件的格式
  42. function upload(): array
  43. {
  44. $i = 0;
  45. foreach ($_FILES as $k => $file) {
  46. // printf('<pre>%s</pre>', print_r($file, true));
  47. foreach ($file['name'] as $k => $v) {
  48. $files[$i]['name'] = $file['name'][$k];
  49. $files[$i]['type'] = $file['type'][$k];
  50. $files[$i]['tmp_name'] = $file['tmp_name'][$k];
  51. $files[$i]['error'] = $file['error'][$k];
  52. $files[$i]['size'] = $file['size'][$k];
  53. $i++;
  54. }
  55. }
  56. // printf('<pre>%s</pre>', print_r($files, true));
  57. return $files;
  58. }

预览效果

效果如下图,结果为临时文件命令移动到存储目录。

临时文件命令移动到存储目录

代码附件

upload.zip大小:2.14KB
已经过安全软件检测无毒,请您放心下载。
本文地址:https://www.mainblog.cn/340.html
版权声明:本文为原创文章,版权归 阁主 所有,欢迎分享本文,转载请保留出处!
免责申明:有些内容源于网络,没能联系到作者。如侵犯到你的权益请告知,我们会尽快删除相关内容。

评论已关闭!