Home Backend Development PHP Tutorial How to use the CI framework to optimize file uploads and upload multiple files

How to use the CI framework to optimize file uploads and upload multiple files

Jun 14, 2018 pm 02:30 PM
ci framework optimization Multiple file upload File Upload

This article mainly introduces the method of CI framework to optimize file upload and multi-file upload. It analyzes in detail the implementation ideas and specific operation steps of CI framework to optimize file upload and multi-file upload in the form of examples. Friends in need can refer to it. Next

The example of this article analyzes the CI framework's method of optimizing file uploads and multiple file uploads. Share it with everyone for your reference, the details are as follows:

I have been studying the Codeigniter framework recently. When writing the file upload in the development project, I found that most programmers use the file upload class of the Codeigniter framework to write the upload method. This code redundancy exists (or the code reuse rate is low and consumes resources.) Therefore, I developed a slightly optimized upload method. And when searching for information, I found that it is difficult to upload multiple files at the same time with the Codeigniter framework, so while optimizing the method, I also studied how to use the Codeigniter framework to upload multiple files at the same time. Let me share it with you. Interested students can pay attention to it. You are welcome to correct any mistakes.

1. Optimize file upload method

The commonly used methods in the Codeigniter manual will not be described again here. Let’s directly talk about how to optimize the method. In order to achieve the purpose of reducing code redundancy and improving code reuse rate.

a) First create a new "upload.php" configuration file in "application/config"

Create a new "upload.php" configuration file in "application/config" and write the uploaded information in it Configuration parameters.

<?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;;
Copy after login

Note: The path folder represented by the upload_path parameter has been created in the project!

b) Load the file upload class in the constructor of the controller

<?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;);
  }
}
Copy after login

Note: The "upload. php” file will be automatically loaded here.

c) Write the upload method and execute the do_upload() method to upload the file

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);
    }
  }
}
Copy after login

Note: Part of the above code is the code in my project , you can ignore and focus directly on the key upload code. When you need to upload different files, you can also configure the file upload in the method, using the $this->upload->initialize() method.

2. Two methods of uploading multiple files at the same time

① Method 1: Loop processing of multiple uploaded files

/**
 * 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();
      }
    }
  }
}
Copy after login

② Method 2: Upload multiple files directly and then process the uploaded data

/**
 * 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>";
    }
  }
}
Copy after login

Which of the two methods is more convenient? Which one is more efficient? You can try it yourself!

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About analysis of CodeIgniter framework verification code library files and usage

About commonly used CI framework encapsulation Image processing method

How to use the CodeIgniter framework to implement image uploading method

The above is the detailed content of How to use the CI framework to optimize file uploads and upload multiple files. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

Simplify file upload processing with Golang functions Simplify file upload processing with Golang functions May 02, 2024 pm 06:45 PM

Answer: Yes, Golang provides functions that simplify file upload processing. Details: The MultipartFile type provides access to file metadata and content. The FormFile function gets a specific file from the form request. The ParseForm and ParseMultipartForm functions are used to parse form data and multipart form data. Using these functions simplifies the file processing process and allows developers to focus on business logic.

In-depth interpretation: Why is Laravel as slow as a snail? In-depth interpretation: Why is Laravel as slow as a snail? Mar 07, 2024 am 09:54 AM

Laravel is a popular PHP development framework, but it is sometimes criticized for being as slow as a snail. What exactly causes Laravel's unsatisfactory speed? This article will provide an in-depth explanation of the reasons why Laravel is as slow as a snail from multiple aspects, and combine it with specific code examples to help readers gain a deeper understanding of this problem. 1. ORM query performance issues In Laravel, ORM (Object Relational Mapping) is a very powerful feature that allows

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Mar 06, 2024 pm 02:33 PM

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Laravel, as a popular PHP framework, provides developers with rich functions and a convenient development experience. However, as the size of the project increases and the number of visits increases, we may face the challenge of performance bottlenecks. This article will delve into Laravel performance optimization techniques to help developers discover and solve potential performance problems. 1. Database query optimization using Eloquent delayed loading When using Eloquent to query the database, avoid

How to implement drag and drop file upload in Golang? How to implement drag and drop file upload in Golang? Jun 05, 2024 pm 12:48 PM

How to implement drag and drop file upload in Golang? Enable middleware; handle file upload requests; create HTML code for the drag and drop area; add JavaScript code for handling drag and drop events.

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Discussion on Golang's gc optimization strategy Discussion on Golang's gc optimization strategy Mar 06, 2024 pm 02:39 PM

Golang's garbage collection (GC) has always been a hot topic among developers. As a fast programming language, Golang's built-in garbage collector can manage memory very well, but as the size of the program increases, some performance problems sometimes occur. This article will explore Golang’s GC optimization strategies and provide some specific code examples. Garbage collection in Golang Golang's garbage collector is based on concurrent mark-sweep (concurrentmark-s

Laravel performance bottleneck revealed: optimization solution revealed! Laravel performance bottleneck revealed: optimization solution revealed! Mar 07, 2024 pm 01:30 PM

Laravel performance bottleneck revealed: optimization solution revealed! With the development of Internet technology, the performance optimization of websites and applications has become increasingly important. As a popular PHP framework, Laravel may face performance bottlenecks during the development process. This article will explore the performance problems that Laravel applications may encounter, and provide some optimization solutions and specific code examples so that developers can better solve these problems. 1. Database query optimization Database query is one of the common performance bottlenecks in Web applications. exist

See all articles