>  기사  >  백엔드 개발  >  PHP에서 여러 파일 업로드를 구현하는 방법

PHP에서 여러 파일 업로드를 구현하는 방법

黄舟
黄舟원래의
2018-05-15 13:43:282250검색

예전 프로젝트를 진행할 때 여러 이미지를 선택하기 위해 양식에 파일 형식 입력을 구현하는 방법이 많았는데, 오늘은 PHP를 기반으로 여러 파일 업로드를 구현하는 방법을 알려 드리겠습니다. 참고하세요

앞서 여러 이미지를 선택할 수 있는 형태로 파일 형식 입력을 구현할 때 최선이 아닐 수 있는 방법을 찾아보시되, 개인 테스트에서는 가능하고 IE7 이상과 크롬 브라우저를 지원합니다

를 이용하세요 일반 다중 파일 선택 양식의 다중 속성

<input type="file" id="image" class="file image hidden" name="image[]" multiple="true">

그런 다음 AjaxFileUpload를 사용하거나 다른 방법으로 제출

해당 명명된 파일$file[‘image']을 인쇄용 json으로 변환

일반 형식

{"name":"7332.png","type":"image\/png","tmp_name":"\/tmp\/phplqppvR","error":0,"size":659}

하지만 이때 결과는

{"name":["7656.png","7718.png"],"type":["image/png","image/png"],"tmp_name":["/tmp/phpDzSovj","/tmp/phpP8kWmT"],"error":[0,0],"size":[357,662]}

All입니다. 속성은 순서대로 배열이 됩니다

이때 다음 코드를 사용할 수 있습니다. 사진 저장 구현

if (!isset($_FILES[$field])) {
  return new JsonResponse(array(&#39;errorCode&#39;=>1, &#39;message&#39;=>&#39;请上传文件&#39;));
}
//重新命名$_FILE 存储多个文件上传
$arrayFile = array();
foreach($_FILES[$field] as $key => $value){
  $i = 0;
  if(is_array($value)) {
    foreach ($value as $v) {
      $i++;
      //重命名后重新放入超全局变量_FILE 保证键名唯一 也可直接上传
      $name = $field . &#39;_split_&#39; . $i;
      $_FILES[$name][$key] = $v;
    }
  }
}
//是否上传多文件
if($i > 0){
  for($j = 1; $j <= $i; $j++){ array_push($arrayFile, $field . &#39;_split_&#39; . $j); } }else{ array_push($arrayFile, $field); } //遍历file多个文件 上传 foreach($arrayFile as $file){ if (isset($_FILES[$file]) && $_FILES[$file][&#39;name&#39;]) { //自定义上传方法 具体内容略 $data = $this->uploadFile($file, $path, uniqid());
    if ( isset($data) && !empty($data) ) {
      if(!isset($data[&#39;errors&#39;])){
        //将上传结果存储于$result中 多图片地址使用逗号拼接
        if(isset($result)){
          $result = array(&#39;errorCode&#39;=>0, &#39;message&#39;=>$result[&#39;message&#39;] . &#39;,&#39; . reset($data));
        }else{
          $result = array(&#39;errorCode&#39;=>0, &#39;message&#39;=>reset($data));
        }
      }else{
        //以下为返回错误信息
        if(is_array(reset($data))){
          $message = reset($data)[0];
        }else{
          $message = reset($data);
        }           
        $result = array(&#39;errorCode&#39; => 1, &#39;message&#39; => $message);
      }
    } else {
      $result = array(&#39;errorCode&#39;=>1, &#39;message&#39;=>&#39;上传失败&#39;);
      break;
    }
  } else {
    $result = array(&#39;errorCode&#39;=>1, &#39;message&#39;=>&#39;请上传文件&#39;);
    break;
  }
}
//返回上传结果
return $result;

요약

위 내용은 PHP에서 여러 파일 업로드를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.