You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter4上传文件自动生成同名文件夹,如何禁用该行为?

问题原因及解决方案

问题根源

你调用move()方法时传入的路径有误:$x_file->move(WRITEPATH.'upload_fs_data/'.$x_file_name) 中,move()的第一个参数要求是目标目录,而非带文件名的完整路径。当你把包含文件名的路径传给第一个参数时,CodeIgniter会将该路径识别为目录名并自动创建,随后把文件以原文件名存入这个新建目录,最终就出现了writeable/fs_upload_data/task.sql/task.sql的嵌套结构。

修正后的代码

public function upload_fs_data_file(){
    if($this->request->getMethod() == "post"){
        $validation = \Config\Services::validation();    
        $rules = [
            "upload_fs_data_file_name" => [
                "label" => "upload_fs_data_file_name", 
                "rules" => 'uploaded[upload_fs_data_file_name]'
            ],
        ];

        if ($this->validate($rules)){
            $x_file = $this->request->getFile('upload_fs_data_file_name');
            // 第一个参数传目标目录,不传第二个参数则保留原文件名
            $x_file->move(WRITEPATH.'upload_fs_data'); 
            // 若需自定义文件名,可传入第二个参数:
            // $x_file->move(WRITEPATH.'upload_fs_data', 'custom_task.sql');
        } else {
            return redirect()->back()
                ->with('errors', $validation->getErrors())
                ->with('warning', 'Invalid Data')
                ->withInput();
        }
    }
}

额外优化说明

  • 移除了重复的if($this->request->getMethod() == "post")判断,精简代码结构。
  • 若目标目录writeable/upload_fs_data不存在,CodeIgniter 4的move()方法会自动创建该目录,无需手动处理。

内容的提问来源于stack exchange,提问作者spreaderman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 15:47:19