• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php实现文件上传的两种方法

php 搞代码 3年前 (2022-01-22) 52次浏览 已收录 0个评论

这篇文章主要为大家详细介绍了两种php文件上传的实现方法,感兴趣的朋友可以参考一下

文件上传一般有下面2种方式:

有两种:
1、标准input表单方式,典型的用$_FILES进行接收;
2、以Base64的方式进行传送,一般是AJAX异步上传。

第一种
标准的input表单方式,适用于大文件进行上传,同时支持批量。html代码关键的几句:

<form enctype="multipart/form-data" method="post" action="upload.php"">  <input type="file" name="id_pic[]" accept="image/*" class="form-control" multiple />  <input type="submit" value="上传 " /></form>

不同的name时:

<form enctype="multipart/form-data" method="post" action="upload.php"">  <input type="file" name="id_pic_1" accept="image/*" class="form-control" />  <input type="file" name="id_pic_2" accept="image/*" class="form-control" />  <input type="submit" value="上传 " /></form>

其中enctype="multipart/form-data"对于文件上传是必不可少的。另外type="file"设置input类型,accept="image/*"指定优先上传图片(MIME 参考手册)。multiple支持一次选多个文件,pic[]以数组的形式接收多个文件。手机端端还可以加入参数capture="camera"选择摄像头拍照上传。

后端处理:
通过$_FILES获取上传的文件。

$files = $_FILES;
传多个文件时,如果name不同,则返回的$_FILES数组格式不同。

name相同时:

array(1) { ["id_pic"] => array(5) {  ["name"] => array(2) {   [0] => string(5) "1.jpg"   [1] => string(5) "2.jpg"  }  ["type"] => array(2) {   [0] => string(10) "image/jpeg"   [1] => string(10) "image/jpeg"  }  ["tmp_name"] => array(2) {   [0] => string(27) "C:\Windows\Temp\php7A7E.tmp"   [1] => string(27) "C:\Windows\Temp\php7A7F.tmp"  }  ["error"] => array(2) {   [0] => int(0)   [1] => int(0)  }  ["size"] => array(2) {   [0] => int(77357)   [1] => int(56720)  } }}

name不相同时:

   array(2) { ["id_pic_1"] => array(5) {  ["name"] => string(5) "1.jpg"  ["type"] => string(10) "image/jpeg"  ["tmp_name"] => string(27) "C:\Windows\Temp\phpBBEE.tmp"  ["error"] => int(0)  ["size"] => int(77357) } ["id_pic_2"] => array(5) {  ["name"] => string(5) "2.jpg"  ["type"] => string(10) "image/jpeg"  ["tmp_name"] => string(27) "C:\Windows\Temp\phpBBEF.tmp"  ["error"] => int(0)  ["size"] => int(56720) }}

在对$_FILES进行foreach遍历时,前面那种输出格式不大方便。后面那种就可以直接遍历。我们可以写个方法进行统一转换:

function dealFiles($files) {    $fileArray = array();    $n     = 0;    foreach ($files as $key=>$file){      if(is_array($file['name'])) {        $keys    =  array_keys($file);        $count   =  count($file['name']);        for ($i=0<strong style="color:transparent">9来源gaodai#ma#com搞@代~码$网</strong>搞gaodaima代码; $i<$count; $i++) {          $fileArray[$n]['key'] = $key;          foreach ($keys as $_key){            $fileArray[$n][$_key] = $file[$_key][$i];          }          $n++;        }      }else{        $fileArray = $files;        break;      }    }    return $fileArray; }

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php实现文件上传的两种方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址