【问题标题】:CodeIgniter file upload change file name inside loopingCodeIgniter 文件上传在循环中更改文件名
【发布时间】:2017-03-23 07:40:42
【问题描述】:

情况是我有 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']

如何做到这一点?

【问题讨论】:

  • 我在哪里没有添加任何条件?我已经在那里输入了case 1: ...case 2: ...case 3: ...。 ://
  • 我已经仔细阅读了您的代码,但仍然没有发现问题。您是否尝试在循环内(在 switch-case 之后)echo $namae 看看会发生什么?
  • 我有一行通过$namae 将其保存到数据库,在行:$this-&gt;model-&gt;simpan_foto($id_survei,$namae,${"photo$n"."_upload"}['file_name']);$namae 的值确实根据我的switch case 进行了更改。所以我猜问题出在$this-&gt;load-&gt;library('upload', $config); 行,$config[] 没有更新到库._.

标签: php codeigniter file-upload codeigniter-3


【解决方案1】:

如果只有三个文件,那么试试这个代码......

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']);
    }
}

【讨论】:

  • 你测试了吗?你能向我解释一下你的代码和我的代码有什么区别吗?因为除了您将switch case 更改为if else 之外,我没有看到任何区别:/
  • 有时 switch case 不起作用我在某些任务中遇到了这个问题,所以
猜你喜欢
  • 1970-01-01
  • 2020-03-31
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 2016-05-28
  • 2012-02-02
  • 1970-01-01
  • 2012-05-25
相关资源
最近更新 更多