php 使用 CodeIgniter 上传多张图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40778683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:14:48  来源:igfitidea点击:

Multiple image upload with CodeIgniter

phpcodeigniterfile-upload

提问by andrew ghosh

I am new user to using code igniter in my project, I am facing one problem while uploading multiple files but the last one only insert to all image three images field.

我是在我的项目中使用代码点火器的新用户,我在上传多个文件时遇到一个问题,但最后一个只插入到所有图像三个图像字段。

my controller is:

我的控制器是:

function products()
    {
     date_default_timezone_set("Asia/Kolkata");
     $config['upload_path'] = './resources/images/products/';
     $config['allowed_types']        = 'gif|jpg|png';
     $config['max_size']             = 1000;
     $config['max_width']            = 1024;
     $config['max_height']           = 768;
     $this->load->library('upload', $config);
     $this->upload->do_upload('userfile');
        $data = array('prod_image' => $this->upload->data(), 
             'prod_image1' => $this->upload->data(),
              'prod_image2' => $this->upload->data());
    $product_image=$data['prod_image']['file_name']; 
    $product_image1=$data['prod_image1']['file_name'];
    $product_image2=$data['prod_image2']['file_name'];

        $data = array(
                'name' => $this->input->post('pd_name'),
                'prod_image' => $product_image,
                'prod_image1' => $product_image1,
                'prod_image2' => $product_image2,
                'created_time' => date('Y-m-d H:i:s'));

        // insert form data into database
        $result_set= $this->tbl_products_model->insertUser($data);

    }       

my view part is:

我的观点是:

<input class="form-control" name="pd_name"type="text"/>
<input type="file"  class="file_upload2" name="userfile"/> //1
<input type="file" class="file_upload2" name="userfile"/> //2
<input type="file" class="file_upload2" name="userfile"/>//3

Please help how to insert 3 images.

请帮助如何插入3张图片。

my datad base like

我的数据库喜欢

===========================================
id|name|prod_image|prod_image1|prod_image2|
===========================================
 1|ard|           |           |          |
============================================

回答by Razib Al Mamun

Html :

网址:

<input type="file" name="userfile[]" multiple="multiple">

PHP :

PHP :

<?php
public function products()
{       
    $this->load->library('upload');
    $dataInfo = array();
    $files = $_FILES;
    $cpt = count($_FILES['userfile']['name']);
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES['userfile']['name']= $files['userfile']['name'][$i];
        $_FILES['userfile']['type']= $files['userfile']['type'][$i];
        $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
        $_FILES['userfile']['error']= $files['userfile']['error'][$i];
        $_FILES['userfile']['size']= $files['userfile']['size'][$i];    

        $this->upload->initialize($this->set_upload_options());
        $this->upload->do_upload();
        $dataInfo[] = $this->upload->data();
    }

    $data = array(
        'name' => $this->input->post('pd_name'),
        'prod_image' => $dataInfo[0]['file_name'],
        'prod_image1' => $dataInfo[1]['file_name'],
        'prod_image2' => $dataInfo[2]['file_name'],
        'created_time' => date('Y-m-d H:i:s')
     );
     $result_set = $this->tbl_products_model->insertUser($data);
}

private function set_upload_options()
{   
    //upload an image options
    $config = array();
    $config['upload_path'] = './resources/images/products/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size']      = '0';
    $config['overwrite']     = FALSE;

    return $config;
}
?>

回答by imtaher

Multiple files uploads unlimited files

多个文件上传无限文件

Database table(profile_images) column names are image_name(255,varcher), added_datetime(current timestamp)

数据库表( profile_images) 列名是image_name(255,varcher), added_datetime(current timestamp)

View

看法

<?php echo validation_errors();?>
<?php echo form_open_multipart('pages/multiple_files');?>
<p><input type="file" multiple="multiple" name="image_name[]" class="form-control" /></p>

<input type="submit" class="btn btn-success btn-block"/> 
</form>

Controller

控制器

public function multiple_files(){
  $this->load->library('upload');
  $image = array();
  $ImageCount = count($_FILES['image_name']['name']);
        for($i = 0; $i < $ImageCount; $i++){
            $_FILES['file']['name']       = $_FILES['image_name']['name'][$i];
            $_FILES['file']['type']       = $_FILES['image_name']['type'][$i];
            $_FILES['file']['tmp_name']   = $_FILES['image_name']['tmp_name'][$i];
            $_FILES['file']['error']      = $_FILES['image_name']['error'][$i];
            $_FILES['file']['size']       = $_FILES['image_name']['size'][$i];

            // File upload configuration
            $uploadPath = './assets/images/profiles/';
            $config['upload_path'] = $uploadPath;
            $config['allowed_types'] = 'jpg|jpeg|png|gif';

            // Load and initialize upload library
            $this->load->library('upload', $config);
            $this->upload->initialize($config);

            // Upload file to server
            if($this->upload->do_upload('file')){
                // Uploaded file data
                $imageData = $this->upload->data();
                 $uploadImgData[$i]['image_name'] = $imageData['file_name'];

            }
        }
         if(!empty($uploadImgData)){
            // Insert files data into the database
            $this->pages_model->multiple_images($uploadImgData);              
        }
  }

Model

模型

  public function multiple_images($image = array()){

     return $this->db->insert_batch('profile_images',$image);
             }

回答by Mayank Pandeyz

The problem is with the following line of code:

问题在于以下代码行:

<input type="file"  class="file_upload2" name="userfile"/> //1
<input type="file" class="file_upload2" name="userfile"/> //2
<input type="file" class="file_upload2" name="userfile"/>//3

These all three have same name.

这三者同名。

To solve this there are two ways:

要解决这个问题,有两种方法:

Give diff name to all 3 input type file

为所有 3 个输入类型文件提供差异名称

Make a single input type file with its multiple file selection true and its name must be an array like:

使具有多个文件选择的单个输入类型文件为真,并且其名称必须是一个数组,例如:

<input type="file" name="filefield[]" multiple="multiple">

Make the following changes and try again.

进行以下更改并重试。

回答by Butani Hardik

code of controller.

控制器代码。

public function upload_multiple($field_name,$path){
    $this->load->library('upload');
    $files = $_FILES;
    $cpt = count($_FILES[$field_name]['name']);//count for number of image files
    $image_name =array();
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES[$field_name]['name']= $files[$field_name]['name'][$i];
        $_FILES[$field_name]['type']= $files[$field_name]['type'][$i];
        $_FILES[$field_name]['tmp_name'] = $files[$field_name]['tmp_name'][$i];
        $_FILES[$field_name]['error']= $files[$field_name]['error'][$i]; 
        $_FILES[$field_name]['size'] = $files[$field_name]['size'][$i];

        $this->upload->initialize($this->set_upload_options($path));
         //for initalizing configuration for each image
        $this->upload->do_upload($field_name);  

        $data = array('upload_data' => $this->upload->data()); 
        $image_name[]=$data['upload_data']['file_name'];
        //store file name into array

    }
    return $image_name;//all images name which is uploaded
}
public function set_upload_options($path)
{   
    $config = array();
    $config['upload_path'] = $path;
    $config['allowed_types'] = '*';
    $config['overwrite']     = FALSE;

    return $config;
}

call function

调用函数

 $image_name=$this->upload_multiple('profile_image',$path=USER_OTHER);//we get all name of uploaded file in $image_name array.