首页 > 开发 > Php > 正文

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

2020-02-21 20:50:42
字体:
来源:转载
供稿:网友

文件上传一般有下面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; $i<$count; $i++) {          $fileArray[$n]['key'] = $key;          foreach ($keys as $_key){            $fileArray[$n][$_key] = $file[$_key][$i];          }          $n++;        }      }else{        $fileArray = $files;        break;      }    }    return $fileArray; }            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表