CodeIgniter文件上传更改文件名在循环

时间:2017-03-23 07:40:43

标签: php codeigniter file-upload codeigniter-3

案例是我有3个文件输入。它们的每个名称属性都是file1file2file3

然后在我的控制器中,我使用switch case函数,我想重命名该文件。

file1 ='标签' file2 ='米' file3 ='rumah'

for ($n=1; $n<=3; $n++) {
    if (empty($_FILES["file$n"]['name'])) continue;

    $filext = pathinfo($_FILES["file$n"]['name'],PATHINFO_EXTENSION);

    switch($n) {
        case 1: $namae = 'label'; break;
        case 2: $namae = 'meter'; break;
        case 3: $namae = 'rumah'; break;
    }

    $config['upload_path']      = $upload_path;
    $config['allowed_types']    = 'gif|jpg|png';
    $config['max_size']         = 1024 * 20;
    $config['file_name']        = $namae;

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

    if (!$this->upload->do_upload("file$n")) {
        ${"photo$n"."_upload"} = $this->upload->display_errors();
    } else {
        ${"photo$n"."_upload"} = $this->upload->data();
        $this->model->simpan_foto($id_survei,$namae,${"photo$n"."_upload"}['file_name']);
    }
}

但它不起作用!所有3个文件都以'label'命名,所以它是label.png,label1.png,label2.png(因为我不使用$config['overwrite']

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

如果只有三个文件而不是尝试此代码....

for ($n=1; $n<=3; $n++) {
    if (empty($_FILES["file$n"]['name'])) continue;

    $filext = pathinfo($_FILES["file$n"]['name'],PATHINFO_EXTENSION);

    if($n==1){
     $namae = 'label';
     }
     if($n==2){
     $namae = 'meter';
     }
     if($n==3){
     $namae = 'rumah';
    }

    $config['upload_path']      = $upload_path;
    $config['allowed_types']    = 'gif|jpg|png';
    $config['max_size']         = 1024 * 20;
    $config['file_name']        = $namae;

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

    if (!$this->upload->do_upload("file$n")) {
        ${"photo$n"."_upload"} = $this->upload->display_errors();
    } else {
        ${"photo$n"."_upload"} = $this->upload->data();
        $this->model->simpan_foto($id_survei,$namae,${"photo$n"."_upload"}['file_name']);
    }
}