在CodeIgniter中上传多个文件

时间:2011-12-04 17:40:01

标签: php codeigniter file-upload

在我的CodeIgniter项目中,我在项目创建期间上传文件。这是上传功能:

function uploadFiles(){

     $this->load->library('upload');  
     $error = 0;    
     $projectName = $_POST['projectname'];
     mkdir('./uploads/'.$projectName);

     for($i=0; $i<count($_FILES); $i++)
     {

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

       $config['upload_path']   = './uploads/'.$projectName;
       $config['allowed_types'] = 'xml|etl';
       $config['max_size']      = '0';
       $config['overwrite']     = TRUE;

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

      if($this->upload->do_upload())
      {
        $error += 0;
      }else{
        $error += 1;
      }
     }

     if($error > 0){ return FALSE; }else{ return TRUE; }

}

我在create_project函数中调用此函数,如下所示:

public function create_project() {
    $this->load->library('form_validation');

    $this->form_validation->set_rules('projectname', 'Project name', 'required');

    $this->form_validation->set_message('required', 'This is an obligatory field');

    if($this->form_validation->run() == FALSE) {
        $this->load->view('project_creation_view');
    } else {
        $this->load->model('Project_management_model');
        $this->Project_management_model->create_project();
        $this->uploadFiles();
    }
}

然而,这没有任何作用。文件未上传。甚至没有创建空目录。有人能帮我找到错误吗?

感谢。

7 个答案:

答案 0 :(得分:22)

您可以上传任意数量的文件..

$config['upload_path'] = 'upload/Main_category_product/';
$path=$config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$this->load->library('upload', $config);

foreach ($_FILES as $fieldname => $fileObject)  //fieldname is the form field name
{
    if (!empty($fileObject['name']))
    {
        $this->upload->initialize($config);
        if (!$this->upload->do_upload($fieldname))
        {
            $errors = $this->upload->display_errors();
            flashMsg($errors);
        }
        else
        {
             // Code After Files Upload Success GOES HERE
        }
    }
}

答案 1 :(得分:2)

这是我修改为上传多个文件的CI_Upload类的扩展,只需将其复制到MY_Upload.php文件即可。它也会创建目录。

http://pastebin.com/g9J6RxW1

然后,您需要在控制器功能中执行的操作是将文件排列到一个数组中,其中字段的名称和键是数组键,配置是数据。在你的情况下像这样:

$project_files['files'][0] = array(
            'upload_path' => './uploads/'.$projectName.'/',
            'max_size' => 0,
            'allowed_types' => 'xml|etl',
            'overwrite' => TRUE,
            'remove_spaces' => TRUE,
        );
$project_files['files'][1] = array(
            'upload_path' => './uploads/'.$projectName.'/',
            'max_size' => 0,
            'allowed_types' => 'xml|etl',
            'overwrite' => TRUE,
            'remove_spaces' => TRUE,
        );

如果所有文件配置相同,只需进行一个for循环来设置它,它也将采用'命名键',即。 $project_files['files']['file_key']

然后打电话:

 if($this->upload->upload_files($project_files)){/*all files uploaded successfully*/}

答案 2 :(得分:1)

由于我的声誉级别,我无法发表评论,但Zoom根据接受的答案对$ fieldname变量进行了评论,该变量是导致错误的数组。我在回答中遇到了同样的问题,发现这是因为我在表单上添加了所有文件输入名称[],这使得php将这些输入作为数组变量。要解决该问题,只需为每个文件输入一个唯一的名称,而不是使其成为PHP数组。在我这样做之后,问题就消失了,接受的答案就像一个魅力。我只是想把这些信息传递给其他任何偶然发现这个问题的人。

答案 3 :(得分:0)

我想你错过了这个:

$config['file_name']     = 'somename_'.$i;
$config['upload_path']   = './uploads/'.$projectName;
...

答案 4 :(得分:0)

以为我之前在这里看过同样的问题;)

尝试输出$ this-&gt; upload-&gt; display_errors(),其中您正在递增$ error变量。那会告诉你究竟出了什么问题。我的钱是关于权限......

答案 5 :(得分:0)

我修改了Cubed Eye的MY_upload以返回上传的所有文件的文件信息。实际上,在调用数据方法时只能访问最后一个文件的信息。我还将上传者的IP地址添加到该列表中。

http://pastebin.com/tG8A85gY

可以通过以下方式使用:

$upload_files = $this->upload->upload_files($project_files);
if ($upload_files->status == true)
{
$fileInfo = $uploaded_files->file_info;
}

我意识到这对于Cubed Eye的编辑会更好,但这是我的第一篇文章,我没有声誉。

答案 6 :(得分:0)

为简单起见,我已经创建了这个CI帮助文件。您可以从配置文件&amp;在项目的任何地方使用。只需要3个参数

@fileobject = HTML文件对象的名称

@fileopath =您要上传的文件路径

@filetypes = default *,ex-&#39; jpg | png | mp4 | pdf&#39;

function fileUploader($fileobject, $filepath = "uploads/", $filetypes = "*"){
// retrieve the number of images uploaded;
$number_of_files = sizeof($_FILES[$fileobject]['tmp_name']);

// considering that do_upload() accepts single files, we will have to do a small hack so that we can upload multiple files. For this we will have to keep the data of uploaded files in a variable, and redo the $_FILE.
$files = $_FILES[$fileobject];

$errors = array();
$file_arr = array();
$result = array();

// first make sure that there is no error in uploading the files
for ($k = 0; $k < $number_of_files; $k++) {
    if ($_FILES[$fileobject]['error'][$k] != 0) $errors[$k][] = 'Couldn\'t upload file ' . $_FILES[$fileobject]['name'][$k];
}
if (sizeof($errors) == 0) {
    // now, taking into account that there can be more than one file, for each file we will have to do the upload
    // we first load the upload library
    $CI =& get_instance();

    $CI->load->library('upload'); // load library

    // next we pass the upload path for the images
    $config['upload_path'] = FCPATH . $filepath;
    // also, we make sure we allow only certain type of images
    $config['allowed_types'] = $filetypes;
    //$config['max_size'] = (int)(ini_get('upload_max_filesize'));
    $config['max_size'] = '10000';
    $config['overwrite'] = FALSE;

    for ($i = 0; $i < $number_of_files; $i++) {
        $_FILES['uploadedimage']['name'] = $files['name'][$i];
        $_FILES['uploadedimage']['type'] = $files['type'][$i];
        $_FILES['uploadedimage']['tmp_name'] = $files['tmp_name'][$i];
        $_FILES['uploadedimage']['error'] = $files['error'][$i];
        $_FILES['uploadedimage']['size'] = $files['size'][$i];
        //now we initialize the upload library
        $CI->upload->initialize($config);
        // we retrieve the number of files that were uploaded
        if ($CI->upload->do_upload('uploadedimage')) {
            $imageup = $CI->upload->data();
           // print_r($imageup["orig_name"]);die;
            array_push($file_arr, $imageup["orig_name"]);
            $result["response"] = "true";
            $result["message"] = "Files uploaded successfully.";
            $result["files"] = $file_arr;

        } else {
            $result["response"] = "false";
            $result["message"][$i] = $CI->upload->display_errors();
        }
    }

} else {
    $result["response"] = "false";
    $result["message"] = $errors;

}
return $result;}

经测试&amp;证实。