使用CodeIgniter 2.0上传多个文件(Array)

时间:2012-07-17 14:12:00

标签: arrays file codeigniter upload

我现在一直在努力寻找并努力工作3天,但我不能。 我想要做的是使用多文件输入表单,然后上传它们。我不能只使用固定数量的文件上传。我在StackOverflow上尝试了很多解决方案,但我找不到工作的解决方案。

这是我的上传控制器

<?php

class Upload extends CI_Controller {

function __construct()
{
    parent::__construct();
    $this->load->helper(array('form', 'url','html'));
}

function index()
{    
    $this->load->view('pages/uploadform', array('error' => ' ' ));
}

function do_upload()
{
    $config['upload_path'] = './Images/';
    $config['allowed_types'] = 'gif|jpg|png';


    $this->load->library('upload');

 foreach($_FILES['userfile'] as $key => $value)
    {

        if( ! empty($key['name']))
        {

            $this->upload->initialize($config);

            if ( ! $this->upload->do_upload($key))
            {
                $error['error'] = $this->upload->display_errors();

                $this->load->view('pages/uploadform', $error);
            }    
            else
            {
                $data[$key] = array('upload_data' => $this->upload->data());

                $this->load->view('pages/uploadsuccess', $data[$key]);


            }
         }

    }    
  }    
 }
 ?> 

我的上传表单是。

 <html>
 <head>
    <title>Upload Form</title>
</head>
<body>

<?php echo $error;?>

<?php echo form_open_multipart('upload/do_upload');?>

<input type="file" multiple name="userfile[]" size="20" />
<br /><br />


<input type="submit" value="upload" />

</form>

</body>
</html> 

我一直有这个错误:

  

您没有选择要上传的文件。

以下是示例的数组:

  

Array([userfile] =&gt; Array([name] =&gt; Array([0] =&gt; youtube.png [1] =&gt; zergling.jpg)[type] =&gt;数组([0 ] =&gt; image / png [1] =&gt; image / jpeg)[tmp_name] =&gt;数组([0] =&gt; E:\ wamp \ tmp \ php7AC2.tmp [1] =&gt; E:\ wamp \ tmp \ php7AC3.tmp)[error] =&gt;数组([0] =&gt; 0 [1] =&gt; 0)[size] =&gt;数组([0] =&gt; 35266 [1] = &gt; 186448)))

如果我选择2个文件,我会连续5次这样做。 我也使用标准的上传库。

17 个答案:

答案 0 :(得分:97)

我终于设法让它在你的帮助下工作了!

这是我的代码:

 function do_upload()
{       
    $this->load->library('upload');

    $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();
    }
}

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

    return $config;
}

谢谢你们!

答案 1 :(得分:4)

您应该使用此库在CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload

中进行多重上传

安装只需将MY_Upload.php文件复制到应用程序库目录即可。

使用:控制器中的函数test_up

public function test_up(){
if($this->input->post('submit')){
    $path = './public/test_upload/';
    $this->load->library('upload');
    $this->upload->initialize(array(
        "upload_path"=>$path,
        "allowed_types"=>"*"
    ));
    if($this->upload->do_multi_upload("myfile")){
        echo '<pre>';
        print_r($this->upload->get_multi_upload_data());
        echo '</pre>';
    }
}else{
    $this->load->view('test/upload_view');
}

}

在applications / view / test文件夹中的upload_view.php

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" id="myfile" multiple>
<input type="submit" name="submit" id="submit" value="submit"/>

答案 2 :(得分:3)

试试这段代码。

它对我来说很好用

每次都要初始化库

    function do_upload()
    {
        foreach ($_FILES as $index => $value)
        {
            if ($value['name'] != '')
            {
                $this->load->library('upload');
                $this->upload->initialize($this->set_upload_options());

                //upload the image
                if ( ! $this->upload->do_upload($index))
                {
                    $error['upload_error'] = $this->upload->display_errors("<span class='error'>", "</span>");

                    //load the view and the layout
                    $this->load->view('pages/uploadform', $error);

                    return FALSE;
                }
                else
                {

                     $data[$key] = array('upload_data' => $this->upload->data());

                     $this->load->view('pages/uploadsuccess', $data[$key]);


                }
            }
        }

    }

    private function set_upload_options()
    {   
        //upload an image options
        $config = array();
        $config['upload_path'] = 'your upload path';
        $config['allowed_types'] = 'gif|jpg|png';

        return $config;
    }

进一步修改

我找到了必须使用一个唯一输入框上传文件的方式

  

CodeIgniter不支持多个文件。在foreach中使用do_upload()与在外部使用它不同。

     

您需要在没有CodeIgniter帮助的情况下处理它。这是一个例子https://github.com/woxxy/FoOlSlide/blob/master/application/controllers/admin/series.php#L331-370

     

https://stackoverflow.com/a/9846065/1171049

这就是你在交流中说的那样:)

答案 3 :(得分:1)

Carlos Rincones建议;不要害怕和超级球员一起比赛。

$files = $_FILES;

for($i=0; $i<count($files['userfile']['name']); $i++)
{
    $_FILES = array();
    foreach( $files['userfile'] as $k=>$v )
    {
        $_FILES['userfile'][$k] = $v[$i];                
    }

    $this->upload->do_upload('userfile')
}

答案 4 :(得分:1)

这里的另一段代码:

参考:https://github.com/stvnthomas/CodeIgniter-Multi-Upload

答案 5 :(得分:0)

    public function imageupload() 
    {

      $count = count($_FILES['userfile']['size']);

  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'gif|jpg|png|bmp';
  $config['max_size']   = '0';
  $config['max_width']  = '0';
  $config['max_height']  = '0';

  $config['image_library'] = 'gd2';
  $config['create_thumb'] = TRUE;
  $config['maintain_ratio'] = FALSE;
  $config['width'] = 50;
  $config['height'] = 50;

  foreach($_FILES as $key=>$value)
  { 
     for($s=0; $s<=$count-1; $s++)
     {
     $_FILES['userfile']['name']=$value['name'][$s];
     $_FILES['userfile']['type']    = $value['type'][$s];
     $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s]; 
     $_FILES['userfile']['error']       = $value['error'][$s];
     $_FILES['userfile']['size']    = $value['size'][$s];  

         $this->load->library('upload', $config);

         if ($this->upload->do_upload('userfile'))
         {
           $data['userfile'][$i] = $this->upload->data();
       $full_path = $data['userfile']['full_path'];


           $config['source_image'] = $full_path;
           $config['new_image'] = './uploads/resiezedImage';

           $this->load->library('image_lib', $config);
           $this->image_lib->resize(); 
           $this->image_lib->clear();

         }
         else
         {
           $data['upload_errors'][$i] = $this->upload->display_errors();
         } 
     }
  }
}

答案 6 :(得分:0)

我在自定义库中使用了以下代码 从我的控制器中拨打,如下所示,

function __construct() {<br />
   &nbsp;&nbsp;&nbsp; parent::__construct();<br />
   &nbsp;&nbsp;&nbsp;   $this->load->library('CommonMethods');<br />
}<br />

$config = array();<br />
$config['upload_path'] = 'assets/upload/images/';<br />
$config['allowed_types'] = 'gif|jpg|png|jpeg';<br />
$config['max_width'] = 150;<br />
$config['max_height'] = 150;<br />
$config['encrypt_name'] = TRUE;<br />
$config['overwrite'] = FALSE;<br />

// upload multiplefiles<br />
$fileUploadResponse = $this->commonmethods->do_upload_multiple_files('profile_picture', $config);
/**
 * do_upload_multiple_files - Multiple Methods
 * @param type $fieldName
 * @param type $options
 * @return type
 */
public function do_upload_multiple_files($fieldName, $options) {

    $response = array();
    $files = $_FILES;
    $cpt = count($_FILES[$fieldName]['name']);
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES[$fieldName]['name']= $files[$fieldName]['name'][$i];
        $_FILES[$fieldName]['type']= $files[$fieldName]['type'][$i];
        $_FILES[$fieldName]['tmp_name']= $files[$fieldName]['tmp_name'][$i];
        $_FILES[$fieldName]['error']= $files[$fieldName]['error'][$i];
        $_FILES[$fieldName]['size']= $files[$fieldName]['size'][$i];    

        $this->CI->load->library('upload');
        $this->CI->upload->initialize($options);

        //upload the image
        if (!$this->CI->upload->do_upload($fieldName)) {
            $response['erros'][] = $this->CI->upload->display_errors();
        } else {
            $response['result'][] = $this->CI->upload->data();
        }
    }

    return $response;
}

答案 7 :(得分:0)

<form method="post" action="<?php echo base_url('submit'); ?>" enctype="multipart/form-data">
    <input type="file" name="userfile[]" id="userfile"  multiple="" accept="image/*">
</form>

MODEL:FilesUpload

class FilesUpload extends CI_Model {

    public function setFiles()
    {
        $name_array = array();
        $count = count($_FILES['userfile']['size']);
        foreach ($_FILES as $key => $value)
            for ($s = 0; $s <= $count - 1; $s++) {
                $_FILES['userfile']['name'] = $value['name'][$s];
                $_FILES['userfile']['type'] = $value['type'][$s];
                $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
                $_FILES['userfile']['error'] = $value['error'][$s];
                $_FILES['userfile']['size'] = $value['size'][$s];

                $config['upload_path'] = 'assets/product/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '10000000';
                $config['max_width'] = '51024';
                $config['max_height'] = '5768';

                $this->load->library('upload', $config);
                if (!$this->upload->do_upload()) {
                    $data_error = array('msg' => $this->upload->display_errors());
                    var_dump($data_error);
                } else {
                    $data = $this->upload->data();
                }
                $name_array[] = $data['file_name'];
            }

        $names = implode(',', $name_array);

        return $names;
    }
}

CONTROLER提交

class Submit extends CI_Controller {
    function __construct()
        {
        parent::__construct();
        $this->load->helper(array('html', 'url'));
        }

        public function index()
        {
        $this->load->model('FilesUpload');

        $data = $this->FilesUpload->setFiles();

        echo '<pre>';
        print_r($data);

    }
}

答案 8 :(得分:0)

        // Change $_FILES to new vars and loop them
        foreach($_FILES['files'] as $key=>$val)
        {
            $i = 1;
            foreach($val as $v)
            {
                $field_name = "file_".$i;
                $_FILES[$field_name][$key] = $v;
                $i++;   
            }
        }
        // Unset the useless one ;)
        unset($_FILES['files']);

        // Put each errors and upload data to an array
        $error = array();
        $success = array();

        // main action to upload each file
        foreach($_FILES as $field_name => $file)
        {
            if ( ! $this->upload->do_upload($field_name))
            {
                echo ' failed ';
            }else{
                echo ' success ';
            }
        }

答案 9 :(得分:0)

所有已发布的文件都将出现在$ _FILES变量中,对于使用codeigniter上传库,我们需要提供我们用于上传的field_name(默认情况下它将是&#39; userfile&#39;),所以我们得到所有发布的文件并创建另一个文件数组,为每个文件创建我们自己的名称,并将此名称赋予codeigniter库do_upload函数。

public String setRedirectURL(){
    return "/redirect/" + this.statusQueryToken;
}

@RequestMapping( /* This should be the return-value of setRedirectURL */)
public URL getRedirectURL(){

}

答案 10 :(得分:0)

function UploadHotelImage(){
        $data = array();
        if($this->input->post('fileSubmit') && !empty($_FILES['userFiles']['name'])){
            $filesCount = count($_FILES['userFiles']['name']);
            for($i = 0; $i < $filesCount; $i++){
                $_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
                $_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
                $_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
                $_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
                $_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];

                $uploadPath = 'uploads/files/';
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] = 'gif|jpg|png';

                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if($this->upload->do_upload('userFile')){
                    $fileData = $this->upload->data();
                    $uploadData[$i]['file_name'] = $fileData['file_name'];
                    $uploadData[$i]['created'] = date("Y-m-d H:i:s");
                    $uploadData[$i]['modified'] = date("Y-m-d H:i:s");
                }
            }

            if(!empty($uploadData)){
                //Insert file information into the database
                $insert = $this->file->insert($uploadData);
                $statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
                $this->session->set_flashdata('statusMsg',$statusMsg);
            }
        }
        //Get files data from database
        $data['files'] = $this->file->getRows();
        //Pass the files data to view
        $this->load->view('upload_files/index', $data);
    }
}


//----- Model-----------//
public function insertHotelImage($data = array()){
        $insert = $this->db->insert_batch('tbl_hotel_images',$data);
        return $insert?true:false;
    }

使用此代码在CI中上传多个图片....

答案 11 :(得分:0)

function imageUpload(){
            if ($this->input->post('submitImg') && !empty($_FILES['files']['name'])) {
                $filesCount = count($_FILES['files']['name']);
                $userID = $this->session->userdata('userID');
                $this->load->library('upload');

                $config['upload_path'] = './userdp/';
                $config['allowed_types'] = 'jpg|png|jpeg';
                $config['max_size'] = '9184928';
                $config['max_width']  = '5000';
                $config['max_height']  = '5000';

                $files = $_FILES;
                $cpt = count($_FILES['files']['name']);

                for($i = 0 ; $i < $cpt ; $i++){
                    $_FILES['files']['name']= $files['files']['name'][$i];
                    $_FILES['files']['type']= $files['files']['type'][$i];
                    $_FILES['files']['tmp_name']= $files['files']['tmp_name'][$i];
                    $_FILES['files']['error']= $files['files']['error'][$i];
                    $_FILES['files']['size']= $files['files']['size'][$i];    

                    $imageName = 'image_'.$userID.'_'.rand().'.png';

                    $config['file_name'] = $imageName;

                    $this->upload->initialize($config);
                    if($this->upload->do_upload('files')){
                        $fileData = $this->upload->data(); //it return
                        $uploadData[$i]['picturePath'] = $fileData['file_name'];
                    }
                }

                if (!empty($uploadData)) {
                    $imgInsert = $this->insert_model->insertImg($uploadData);
                    $statusMsg = $imgInsert?'Files uploaded successfully.':'Some problem occurred, please try again.';
                    $this->session->set_flashdata('statusMsg',$statusMsg);
                    redirect('home/user_dash');
                }
            }
            else{
                redirect('home/user_dash');
            }
        }

                            

答案 12 :(得分:0)

codeigniter中没有预定义的方法可以一次上传多个文件,但您可以将数据发送到数组并逐个上传

这里是参考:这是在codeigniter 3.0.1中使用预览https://codeaskbuzz.com/how-to-upload-multiple-file-in-codeigniter-framework/

上传多个文件的最佳选项

答案 13 :(得分:0)

所以我要更改的是每次都加载上载库

                $config = array();
                $config['upload_path'] = $filePath;
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size']      = '0';
                $config['overwrite']     = FALSE;

                $files = $_FILES;
                $count = count($_FILES['nameUpload']['name']);


                for($i=0; $i<$count; $i++)
                {
                    $this->load->library('upload', $config);

                    $_FILES['nameUpload']['name']= $files['nameUpload']['name'][$i];
                    $_FILES['nameUpload']['type']= $files['nameUpload']['type'][$i];
                    $_FILES['nameUpload']['tmp_name']= $files['nameUpload']['tmp_name'][$i];
                    $_FILES['nameUpload']['error']= $files['nameUpload']['error'][$i];
                    $_FILES['nameUpload']['size']= $files['nameUpload']['size'][$i];

                    $this->upload->do_upload('nameUpload');
                }

对我有用。

答案 14 :(得分:0)

对于CodeIgniter 3

<form action="<?php echo base_url('index.php/TestingController/insertdata') ?>" method="POST"
      enctype="multipart/form-data">
    <div class="form-group">
        <label for="">title</label>
        <input type="text" name="title" id="title" class="form-control">
    </div>
    <div class="form-group">
        <label for="">File</label>
        <input type="file" name="files" id="files" class="form-control">
    </div>
    <input type="submit" value="Submit" class="btn btn-primary">
</form>


public function insertdatanew()
{
    $this->load->library('upload');
    $files = $_FILES;
    $cpt = count($_FILES['filesdua']['name']);

    for ($i = 0; $i < $cpt; $i++) {
        $_FILES['filesdua']['name'] = $files['filesdua']['name'][$i];
        $_FILES['filesdua']['type'] = $files['filesdua']['type'][$i];
        $_FILES['filesdua']['tmp_name'] = $files['filesdua']['tmp_name'][$i];
        $_FILES['filesdua']['error'] = $files['filesdua']['error'][$i];
        $_FILES['filesdua']['size'] = $files['filesdua']['size'][$i];

        // fungsi uploud
        $config['upload_path']          = './uploads/testing/';
        $config['allowed_types']        = '*';
        $config['max_size']             = 0;
        $config['max_width']            = 0;
        $config['max_height']           = 0;
        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if (!$this->upload->do_upload('filesdua')) {
            $error = array('error' => $this->upload->display_errors());
            var_dump($error);

            // $this->load->view('welcome_message', $error);
        } else {

            // menambil nilai value yang di upload  
            $data = array('upload_data' => $this->upload->data());
            $nilai = $data['upload_data']; 
            $filename = $nilai['file_name'];
            var_dump($filename);

            // $this->load->view('upload_success', $data);
        }
    }
    // var_dump($cpt);
}

答案 15 :(得分:-1)

保存,然后将变量$ _FILES重新定义为您需要的任何内容。 也许不是最好的解决方案,但这对我有用。

function do_upload()
{

    $this->load->library('upload');
    $this->upload->initialize($this->set_upload_options());

    $quantFiles = count($_FILES['userfile']['name']);


    for($i = 0; $i < $quantFiles ; $i++)
    {
        $arquivo[$i] = array
                    (
                        'userfile' => array 
                                        (
                                            'name' => $_FILES['userfile']['name'][$i],
                                            'type' => $_FILES['userfile']['type'][$i],
                                            'tmp_name' => $_FILES['userfile']['tmp_name'][$i],
                                            'error' => $_FILES['userfile']['error'][$i],
                                            'size' => $_FILES['userfile']['size'][$i]
                                        )
                    );
    }


    for($i = 0; $i < $quantFiles ; $i++)
    {
        $_FILES = '';
        $_FILES = $arquivo[$i];



        if ( ! $this->upload->do_upload())
        {
            $error[$i] = array('error' => $this->upload->display_errors());


            return FALSE;
        }
        else
        {

            $data[$i] = array('upload_data' => $this->upload->data());

            var_dump($this->upload->data());
        }


    }





    if(isset($error))
        {
            $this->index($error);
        }
        else
        {
            $this->index($data);
        }

}

建立配置的单独函数..

private function set_upload_options()
{   
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'xml|pdf';
    $config['max_size'] = '10000';

    return $config;
}

答案 16 :(得分:-1)

我最近在研究它。试试这个功能:

/**
 * @return array an array of your files uploaded.
 */
private function _upload_files($field='userfile'){
    $files = array();
    foreach( $_FILES[$field] as $key => $all )
        foreach( $all as $i => $val )
            $files[$i][$key] = $val;

    $files_uploaded = array();
    for ($i=0; $i < count($files); $i++) { 
        $_FILES[$field] = $files[$i];
        if ($this->upload->do_upload($field))
            $files_uploaded[$i] = $this->upload->data($files);
        else
            $files_uploaded[$i] = null;
    }
    return $files_uploaded;
}

在你的情况下:

<input type="file" multiple name="images[]" size="20" />

<input type="file" name="images[]">
<input type="file" name="images[]">
<input type="file" name="images[]">

在控制器中:

public function do_upload(){
    $config['upload_path'] = './Images/';
    $config['allowed_types'] = 'gif|jpg|png';
    //...

    $this->load->library('upload',$config);

    if ($_FILES['images']) {
        $images= $this->_upload_files('images');
        print_r($images);
    }
}

PHP手册的一些基本参考:PHP file upload