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

CodeIgniter中如何将多图隐藏输入值从视图传至控制器?

我来帮你搞定这个CodeIgniter里的图片展示、上传和AJAX删除需求,咱们一步步拆解实现:

完整实现方案

1. 视图层(updt-project-details.php)处理

这部分要完成:展示已上传图片、添加文件上传控件、传递隐藏的图片名、处理无图片时的提示,同时验证图片扩展名有效性。

<div class="row">
    <div class="col-sm-8">
        <!-- 多文件上传控件,限制仅图片类型 -->
        <input type="file" name="docs[]" multiple="multiple" accept="image/jpeg,image/png,image/gif">
        
        <!-- 已上传图片展示区域 -->
        <div id="existing-images" class="mt-3">
            <?php 
            // 从数据库取出已存储的图片列表(假设$ans[0]->docs是逗号分隔的图片名字符串)
            $existing_docs = !empty($ans[0]->docs) ? explode(',', $ans[0]->docs) : [];
            $allowed_ext = ['jpg', 'jpeg', 'png', 'gif']; // 允许的图片扩展名
            
            if (!empty($existing_docs)) {
                foreach ($existing_docs as $doc) {
                    // 验证文件扩展名是否合法
                    $file_ext = strtolower(pathinfo($doc, PATHINFO_EXTENSION));
                    if (in_array($file_ext, $allowed_ext)) {
                        $img_url = base_url('uploads/' . $doc); // 图片访问路径
            ?>
                        <div class="img-container d-inline-block m-2 position-relative">
                            <img src="<?= $img_url ?>" alt="Project Document" style="width:150px;height:150px;object-fit:cover;">
                            <!-- 隐藏字段:把已有的图片名传递给控制器 -->
                            <input type="hidden" name="existing_docs[]" value="<?= $doc ?>">
                            <!-- 删除按钮:绑定图片文件名用于AJAX删除 -->
                            <button class="btn btn-danger btn-sm position-absolute top-0 end-0 delete-img" data-filename="<?= $doc ?>">×</button>
                        </div>
            <?php 
                    }
                }
            } else {
                // 无图片时显示提示
                echo '<p class="text-muted">no documents found</p>';
            }
            ?>
        </div>
    </div>
</div>

2. AJAX实现图片删除功能

用jQuery写前端逻辑,点击删除按钮后异步请求控制器删除文件,同时更新页面显示:

<script>
$(document).ready(function() {
    // 绑定删除按钮点击事件
    $(document).on('click', '.delete-img', function() {
        const filename = $(this).data('filename');
        if (confirm('确定要删除这张图片吗?')) {
            $.ajax({
                url: "<?= site_url('project/delete_image') ?>", // 控制器方法路径
                type: "POST",
                data: { filename: filename },
                dataType: "json",
                success: function(res) {
                    if (res.success) {
                        // 移除当前图片容器
                        $(`.delete-img[data-filename="${filename}"]`).closest('.img-container').remove();
                        // 检查是否还有剩余图片,无图则显示提示
                        if ($('#existing-images .img-container').length === 0) {
                            $('#existing-images').html('<p class="text-muted">no documents found</p>');
                        }
                        alert('图片删除成功');
                    } else {
                        alert(`删除失败:${res.message}`);
                    }
                },
                error: function() {
                    alert('请求出错,请稍后重试');
                }
            });
        }
    });
});
</script>

3. 控制器层处理

在你的项目控制器(比如Project.php)里写两个核心方法:处理项目详情更新(含图片上传)、处理AJAX删除图片。

3.1 更新项目详情方法

public function update_project_details() {
    // 加载所需库
    $this->load->library('form_validation');
    $this->load->library('upload');
    
    // 表单验证规则(根据你的业务调整)
    $this->form_validation->set_rules('project_id', 'Project ID', 'required');
    
    if ($this->form_validation->run() === FALSE) {
        // 验证失败,返回编辑页面
        $project_id = $this->input->post('project_id');
        $data['ans'] = $this->project_model->get_project($project_id);
        $this->load->view('updt-project-details', $data);
    } else {
        // 配置文件上传参数
        $upload_config = [
            'upload_path' => './uploads/',
            'allowed_types' => 'jpg|jpeg|png|gif',
            'max_size' => 2048 // 限制2MB以内
        ];
        $this->upload->initialize($upload_config);
        
        $uploaded_files = [];
        // 获取已有的图片列表
        $existing_docs = $this->input->post('existing_docs') ?? [];
        
        // 处理新上传的多文件
        if (!empty($_FILES['docs']['name'][0])) {
            foreach ($_FILES['docs']['name'] as $key => $name) {
                // 重命名临时文件数组,适配CodeIgniter上传库
                $_FILES['single_doc'] = [
                    'name' => $_FILES['docs']['name'][$key],
                    'type' => $_FILES['docs']['type'][$key],
                    'tmp_name' => $_FILES['docs']['tmp_name'][$key],
                    'error' => $_FILES['docs']['error'][$key],
                    'size' => $_FILES['docs']['size'][$key]
                ];
                
                if ($this->upload->do_upload('single_doc')) {
                    $upload_data = $this->upload->data();
                    $uploaded_files[] = $upload_data['file_name'];
                } else {
                    // 上传失败,返回错误提示
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect('project/update/' . $this->input->post('project_id'));
                }
            }
        }
        
        // 合并已有图片和新上传图片,转成逗号分隔字符串存入数据库
        $all_docs = array_merge($existing_docs, $uploaded_files);
        $docs_str = implode(',', $all_docs);
        
        // 更新数据库
        $update_data = [
            'docs' => $docs_str,
            // 其他需要更新的字段...
        ];
        $this->project_model->update_project($this->input->post('project_id'), $update_data);
        
        $this->session->set_flashdata('success', '项目详情更新成功');
        redirect('project/details/' . $this->input->post('project_id'));
    }
}

3.2 AJAX删除图片方法

public function delete_image() {
    $this->output->set_content_type('application/json');
    
    // 验证是否为AJAX请求
    if (!$this->input->is_ajax_request()) {
        $this->output->set_output(json_encode(['success' => false, 'message' => '非法请求']));
        return;
    }
    
    $filename = $this->input->post('filename');
    $file_path = './uploads/' . $filename;
    
    if (file_exists($file_path)) {
        if (unlink($file_path)) {
            // 可选:立即从数据库移除该图片记录(需要传递项目ID,可通过AJAX参数补充)
            // $project_id = $this->input->post('project_id');
            // $this->project_model->remove_doc_from_project($project_id, $filename);
            
            $this->output->set_output(json_encode(['success' => true, 'message' => '删除成功']));
        } else {
            $this->output->set_output(json_encode(['success' => false, 'message' => '无法删除文件']));
        }
    } else {
        $this->output->set_output(json_encode(['success' => false, 'message' => '文件不存在']));
    }
}

4. 模型层辅助方法(可选)

如果需要立即从数据库移除删除的图片记录,可以在模型里加这个方法:

public function remove_doc_from_project($project_id, $filename) {
    $project = $this->get_project($project_id);
    $docs = explode(',', $project->docs);
    // 过滤掉要删除的图片名
    $docs = array_filter($docs, function($doc) use ($filename) {
        return $doc !== $filename;
    });
    $docs_str = implode(',', $docs);
    return $this->db->where('id', $project_id)->update('projects', ['docs' => $docs_str]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:13:10