之前在實(shí)現(xiàn)表單中file類型input選擇多圖片的時(shí)候找到一種方式 也許不是最好的但親測可行且支持ie7以上以及chrome瀏覽器
在表單中使用正常多文件選擇multiple屬性
<input type="file" id="image" class="file image hidden" name="image[]" multiple="true">
然后使用AjaxFileUpload或其他方式提交
將對應(yīng)命名的file文件 $file[‘image'] 轉(zhuǎn)化為 json打印
正常格式
{"name":"7332.png","type":"image//png","tmp_name":"http://tmp//phplqppvR","error":0,"size":659}但是此時(shí)結(jié)果為
{"name":["7656.png","7718.png"],"type":["image/png","image/png"],"tmp_name":["/tmp/phpDzSovj","/tmp/phpP8kWmT"],"error":[0,0],"size":[357,662]}所有的屬性都變?yōu)閿?shù)組 按序排列
這時(shí)候可以使用以下代碼實(shí)現(xiàn)圖片保存
if (!isset($_FILES[$field])) { return new JsonResponse(array('errorCode'=>1, 'message'=>'請上傳文件'));}//重新命名$_FILE 存儲(chǔ)多個(gè)文件上傳$arrayFile = array();foreach($_FILES[$field] as $key => $value){ $i = 0; if(is_array($value)) { foreach ($value as $v) { $i++; //重命名后重新放入超全局變量_FILE 保證鍵名唯一 也可直接上傳 $name = $field . '_split_' . $i; $_FILES[$name][$key] = $v; } }}//是否上傳多文件if($i > 0){ for($j = 1; $j <= $i; $j++){ array_push($arrayFile, $field . '_split_' . $j); } }else{ array_push($arrayFile, $field); } //遍歷file多個(gè)文件 上傳 foreach($arrayFile as $file){ if (isset($_FILES[$file]) && $_FILES[$file]['name']) { //自定義上傳方法 具體內(nèi)容略 $data = $this->uploadFile($file, $path, uniqid()); if ( isset($data) && !empty($data) ) { if(!isset($data['errors'])){ //將上傳結(jié)果存儲(chǔ)于$result中 多圖片地址使用逗號拼接 if(isset($result)){ $result = array('errorCode'=>0, 'message'=>$result['message'] . ',' . reset($data)); }else{ $result = array('errorCode'=>0, 'message'=>reset($data)); } }else{ //以下為返回錯(cuò)誤信息 if(is_array(reset($data))){ $message = reset($data)[0]; }else{ $message = reset($data); } $result = array('errorCode' => 1, 'message' => $message); } } else { $result = array('errorCode'=>1, 'message'=>'上傳失敗'); break; } } else { $result = array('errorCode'=>1, 'message'=>'請上傳文件'); break; }}//返回上傳結(jié)果return $result;總結(jié)
以上所述是小編給大家介紹的PHP 實(shí)現(xiàn)一種多文件上傳的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答