>  기사  >  백엔드 개발  >  CI 프레임워크를 사용하여 파일 업로드를 최적화하고 여러 파일을 업로드하는 방법

CI 프레임워크를 사용하여 파일 업로드를 최적화하고 여러 파일을 업로드하는 방법

不言
不言원래의
2018-06-14 14:30:192050검색

이 글에서는 파일 업로드와 다중 파일 업로드를 최적화하기 위한 CI 프레임워크의 방법을 주로 소개하며, 파일 업로드와 다중 파일 업로드를 최적화하기 위한 CI 프레임워크의 구현 아이디어와 구체적인 작동 단계를 예시 형식으로 자세히 분석합니다. 필요하신 분들은 참고하시면 됩니다

이 글에서는 CI 프레임워크의 파일 업로드 최적화 방법과 다중 파일 업로드 방법을 예시를 통해 분석합니다. 참고하실 수 있도록 자세한 내용은 다음과 같습니다.

최근 Codeigniter 프레임워크에 대해 공부하고 있는데, 개발 프로젝트에서 파일 업로드를 작성할 때 대부분의 프로그래머가 Codeigniter 프레임워크의 파일 업로드 클래스를 사용하는 것을 발견했습니다. 업로드 방법을 작성합니다. 중복되는(또는 코드 재사용률이 낮고 리소스가 소모됩니다.) 따라서 약간 최적화된 업로드 방법을 개발했습니다. 그리고 정보 검색을 해보니 Codeigniter 프레임워크로는 여러 파일을 동시에 업로드하는 것이 어렵다는 것을 알게 되었기 때문에 방법을 최적화하면서 Codeigniter 프레임워크를 사용하여 여러 파일을 동시에 업로드하는 방법도 연구했습니다. 관심 있는 학생들은 주의를 기울여서 내용을 공유해 주십시오. 실수가 있으면 바로잡아 주십시오.

1. 파일 업로드 방법 최적화

코드이그나이터 매뉴얼에서 일반적으로 사용되는 방법은 여기서 다시 설명하지 않습니다. 코드 중복을 줄이고 코드 재사용률을 높이기 위한 방법을 직접 설명하겠습니다.

a) 먼저 " application/config "에 새로운 " upload.php " 구성 파일을 생성합니다.

" application/config "에 새로운 " upload.php" 구성 파일을 생성하고 그 안에 업로드된 구성 매개변수를 작성합니다.

<?php
  defined(&#39;BASEPATH&#39;) OR exit(&#39;No direct script access allowed&#39;);
  //上传的参数配置
  $config[&#39;upload_path&#39;] = &#39;./public/uploads/&#39;;
  $config[&#39;allowed_types&#39;] = &#39;gif|png|jpg&#39;;
  $config[&#39;max_size&#39;] = 100;
  $config[&#39;max_width&#39;] = &#39;1024&#39;;
  $config[&#39;max_height&#39;] = &#39;768&#39;;

참고: upload_path 매개변수로 표시되는 경로 폴더는 프로젝트에 이미 생성되었습니다!

b) 컨트롤러 생성자에서 파일 업로드 클래스를 로드합니다

<?php
defined(&#39;BASEPATH&#39;) OR exit(&#39;No direct script access allowed&#39;);
/**
 * 控制器
 */
class Brand extends Admin_Controller
{
  public function __construct()
  {
    parent::__construct();
    $this->load->model(&#39;brand_model&#39;);
    $this->load->library(&#39;form_validation&#39;);
    //激活分析器以调试程序
    $this->output->enable_profiler(TRUE);
    //配置中上传的相关参数会自动加载
    $this->load->library(&#39;upload&#39;);
  }
}

참고: 첫 번째 단계에서 생성한 "upload.php" 파일의 업로드 구성 정보가 여기에 자동으로 로드됩니다.

c) 업로드 메소드를 작성하고 do_upload() 메소드를 실행하여 파일을 업로드합니다

public function insert()
{
  //设置验证规则
  $this->form_validation->set_rules(&#39;brand_name&#39;,&#39;名称&#39;,&#39;required&#39;);
  if($this->form_validation->run() == false){
    //未通过验证
    $data[&#39;message&#39;] = validation_errors();
    $data[&#39;wait&#39;] = 3;
    $data[&#39;url&#39;] = site_url(&#39;admin/brand/add&#39;);
    $this->load->view(&#39;message.html&#39;,$data);
  }else{
    //通过验证,处理图片上传
    if ($this->upload->do_upload(&#39;logo&#39;)) { //logo为前端file控件名
      //上传成功,获取文件名
      $fileInfo = $this->upload->data();
      $data[&#39;logo&#39;] = $fileInfo[&#39;file_name&#39;];
      //获取表单提交数据
      $data[&#39;brand_name&#39;] = $this->input->post(&#39;brand_name&#39;);
      $data[&#39;url&#39;] = $this->input->post(&#39;url&#39;);
      $data[&#39;brand_desc&#39;] = $this->input->post(&#39;brand_desc&#39;);
      $data[&#39;sort_order&#39;] = $this->input->post(&#39;sort_order&#39;);
      $data[&#39;is_show&#39;] = $this->input->post(&#39;is_show&#39;);
      //调用模型完成添加动作
      if($this->brand_model->add_brand($data)){
        $data[&#39;message&#39;] = "添加成功";
        $data[&#39;wait&#39;] = 3;
        $data[&#39;url&#39;] = site_url(&#39;admin/brand/index&#39;);
        $this->load->view(&#39;message.html&#39;,$data);
      }else{
        $data[&#39;message&#39;] = "添加失败";
        $data[&#39;wait&#39;] = 3;
        $data[&#39;url&#39;] = site_url(&#39;admin/brand/add&#39;);
        $this->load->view(&#39;message.html&#39;,$data);
      }
    }else{
      //上传失败
      $data[&#39;message&#39;] = $this->upload->display_errors();
      $data[&#39;wait&#39;] = 3;
      $data[&#39;url&#39;] = site_url(&#39;admin/brand/add&#39;);
      $this->load->view(&#39;message.html&#39;,$data);
    }
  }
}

참고: 위 코드 중 일부는 내 프로젝트의 코드이므로 무시하고 키 업로드 코드에 직접 집중할 수 있습니다. . 다른 파일을 업로드해야 하는 경우 $this->upload->initialize() 메소드를 사용하여 메소드에서 파일 업로드를 구성할 수도 있습니다.

2. 여러 파일을 동시에 업로드하는 두 가지 방법

① 방법 1: 업로드된 여러 파일을 반복

/**
 * Codeigniter框架实现多文件上传
 * @author Zhihua_W
 * 方法一:对上传的文件进行循环处理
 */
public function multiple_uploads1()
{
  //载入所需文件上传类库
  $this->load->library(&#39;upload&#39;);
  //配置上传参数
  $upload_config = array(
    &#39;upload_path&#39; => &#39;./public/uploads/&#39;,
    &#39;allowed_types&#39; => &#39;jpg|png|gif&#39;,
    &#39;max_size&#39; => &#39;500&#39;,
    &#39;max_width&#39; => &#39;1024&#39;,
    &#39;max_height&#39; => &#39;768&#39;,
  );
  $this->upload->initialize($upload_config);
  //循环处理上传文件
  foreach ($_FILES as $key => $value) {
    if (!empty($key[&#39;name&#39;])) {
      if ($this->upload->do_upload($key)) {
        //上传成功
        print_r($this->upload->data());
      } else {
        //上传失败
        echo $this->upload->display_errors();
      }
    }
  }
}

② 방법 2: 여러 파일을 한꺼번에 업로드한 후 처리 업로드된 데이터

/**
 * Codeigniter框架实现多文件上传
 * @author Zhihua_W
 * 方法二:直接一下将多个文件全部上传然后在对上传过的数据进行处理
 */
public function multiple_uploads2()
{
  $config[&#39;upload_path&#39;] = &#39;./public/uploads/&#39;;
  //这里的public是相对于index.php的,也就是入口文件,这个千万不能弄错!
  //否则就会报错:"The upload path does not appear to be valid.";
  $config[&#39;allowed_types&#39;] = &#39;gif|jpg|png&#39;;
  //我试着去上传其它类型的文件,这里一定要注意顺序!
  //否则报错:"A problem was encountered while attempting to move the uploaded file to the final destination."
  //这个错误一般是上传文件的文件名不能是中文名,这个很郁闷!还未解决,大家可以用其它方法,重新改一下文件名就可以解决了!
  //$config[&#39;allowed_types&#39;] = &#39;zip|gz|png|gif|jpg&#39;;(正确)
  //$config[&#39;allowed_types&#39;] = &#39;png|gif|jpg|zip|gz&#39;;(错误)
  $config[&#39;max_size&#39;] = &#39;1024&#39;;
  $config[&#39;max_width&#39;] = &#39;1024&#39;;
  $config[&#39;max_height&#39;] = &#39;768&#39;;
  $config[&#39;file_name&#39;] = time(); //文件名不使用原始名
  $this->load->library(&#39;upload&#39;, $config);
  if (!$this->upload->do_upload()) {
    echo $this->upload->display_errors();
  } else {
    $data[&#39;upload_data&#39;] = $this->upload->data(); //上传文件的一些信息
    $img = $data[&#39;upload_data&#39;][&#39;file_name&#39;]; //取得文件名
    echo $img . "<br>";
    foreach ($data[&#39;upload_data&#39;] as $item => $value) {
      echo $item . ":" . $value . "<br>";
    }
  }
}

두 가지 방법 중 어떤 방법이 더 편리한가요? 어느 것이 더 효율적인가요? 직접 시도해 볼 수 있습니다!

위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되었으면 좋겠습니다. 더 많은 관련 내용은 PHP 중국어 홈페이지를 주목해주세요!

관련 권장사항:

CodeIgniter 프레임워크 검증 코드 라이브러리 파일 분석 및 사용법에 대해

일반적으로 사용되는 이미지 처리 방법의 CI 프레임워크 캡슐화에 대해

CodeIgniter 프레임워크를 사용하여 이미지 업로드를 구현하는 방법 방법

위 내용은 CI 프레임워크를 사용하여 파일 업로드를 최적화하고 여러 파일을 업로드하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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