提交表单后如何将上传文件保存至指定文件夹并存储相关数据
解决方案
前置准备
- 在你的CodeIgniter项目根目录新建文件夹
uploads/resumes,并将该文件夹权限设置为755,确保服务端程序有写入权限。 - 检查你的表单路由配置,确认
action填写的careerform可以正确指向savecareer控制器方法。
控制器代码修改
你原有代码直接通过$this->input->post('resume')获取上传文件是错误的,文件上传数据无法通过post方法直接获取,需要调用CodeIgniter内置的上传类处理,修改后的完整savecareer方法代码如下:
public function savecareer(){ $this->load->config('email'); $this->load->library('email'); // 加载上传类 $this->load->library('upload'); $from = '你的通知邮箱地址'; // 这里替换成实际的发件人邮箱 $to = $this->input->post('email'); $subject = '简历投递通知'; $firstname = $this->input->post('firstname'); $lastname = $this->input->post('lastname'); $phone = $this->input->post('phone'); $department = $this->input->post('department'); $comment = $this->input->post('comment'); // 配置上传参数 $upload_config = [ 'upload_path' => FCPATH . 'uploads/resumes/', // FCPATH是CI常量,指向项目根目录 'allowed_types' => 'pdf', // 仅允许pdf格式,和表单accept属性对应 'max_size' => 2048, // 最大2MB,可根据需求调整 'file_name' => time() . '_' . preg_replace('/\s+/', '_', $_FILES['resume']['name']) // 重命名文件,避免同名覆盖 ]; $this->upload->initialize($upload_config); $resume_name = ''; // 处理上传逻辑 if ($this->upload->do_upload('resume')) { // 上传成功,获取处理后的文件名 $upload_data = $this->upload->data(); $resume_name = $upload_data['file_name']; } else { // 上传失败的处理逻辑,可根据需求跳转回表单页提示错误 $this->session->set_flashdata('error', '简历上传失败:' . $this->upload->display_errors()); redirect($_SERVER['HTTP_REFERER']); exit; } $message = '姓名:'.$firstname.' '.$lastname.'<br> 手机号:'.$phone.' <br> 邮箱:'.$to.'<br> 投递部门:'.$department.'<br> 留言:'.$comment; $this->email->set_newline("\r\n"); $this->email->from($to); $this->email->to($from); $this->email->subject($subject); $this->email->message($message); // 如果需要把简历作为邮件附件发送,取消下面这行注释 // $this->email->attach($upload_data['full_path']); $this->email->send(); $data = array( 'firstname' => $firstname, 'lastname' => $lastname, 'phone' => $phone, 'email' => $to, 'department' => $department, 'resume' => $resume_name, // 存储处理后的文件名到数据库 'comment' => $comment ); // 插入数据到数据库 $this->db->insert('tp_career',$data); $this->session->set_flashdata('success', '简历投递成功。'); redirect("thankyou-career"); }
其他注意事项
- 你的表单中上传文件字段的属性写的是
require,正确的必填属性应为required,可自行修正避免兼容性问题。 - 如果后续需要在前端展示简历,直接拼接地址
base_url('uploads/resumes/'.$resume_name)即可访问。
内容的提问来源于stack exchange,提问作者Kishore Sharma
相关产品推荐
相关产品推荐

