duancunsu9209 2015-03-10 08:08
浏览 59

使用Ajax和jQuery在CodeIgniter PHP中上传文件

I am trying to send/ upload a value from an file type input along with data from text inputs to the my do_upload() function in CodeIgniter.

I been researching here and on other websites about how to do this and applied the codes in mine, but with no luck yet, it still won't work. I do not want to use FormData since I don't wanna add a <form> element on my "form".

Here is my jQuery and Ajax:

$("#create_post").click(function(e){
    var post_title = document.getElementById("post_title").value;
    var post_image = document.getElementById("post_image").value;
    var post_content = document.getElementById("post_content").value;
    var post_labels = document.getElementById("post_labels").value;
    if(post_title === "" && post_content === ""){
        return;
    }else{
        $.ajax({
            type: "post",
            url: "./create/process_create",
            enctype: 'multipart/form-data',
            data: "post_title="+post_title+"&post_image="+post_image+"&post_content="+post_content+"&post_labels="+post_labels,
            success: function(data){
                $('#stage').hide();
                var stage = document.getElementById('stage');
                stage.innerHTML = data;
                $('#stage').show(500);
            }
        });
    }
});

My CodeIgniter Handler:

public function process_create(){
        $file = $this->input->post('post_image');
        if(!empty($file)){
            $image_name = $this->input->post('post_title').'_'.$this->main_model->get_unique_number();

            $result = $this->do_upload($image_name);

            if($result['result'] == 'success'){
                $image_name = $result['file_name'];
                $url = $this->main_model->create($image_name);
                if($url){
                    redirect('/'.$url);
                }
            }
        }else{
            echo 'Empty.';
            $url = $this->main_model->create();
            if($url){
                redirect('/'.$url);
            }
        }

        return FALSE;
    }

    public function do_upload($file_name){
        $config['upload_path'] = './images/uploads/';
        $config['allowed_types'] = 'gif|jpg|jpeg|png|JPEG|JPG|PNG';
        $config['file_name'] = $file_name;
        $config['max_size'] = '500';
        $config['max_width'] = '500';
        $config['max_height'] = '500';

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

        if(!$this->upload->do_upload('post_image')){
            //if the upload has failed
            $title = 'Image Upload Error';
            $error = array('error' => $this->upload->display_errors());

            $this->load->view('error', $error);

            $result['result'] = 'failed';

            return $result;
        }else{
            //if the upload was successful
            $image_data = $this->upload->data();
            $image_name = $image_data['file_name'];

            $result['file_name'] = $image_name;
            $result['result'] = 'success';
            echo 'Success';
            return $result;
        }
    }

My HTML:

<div class='form-group'>
    <label for='post_title'>Title:</label>
    <input type='text' class='form-control' name='post_title' id='post_title' placeholder='Type title here...'>
</div>
<div class='form-group'>
    <label for='post_image'>Select photo:</label>
    <input type='file' name='post_image' id='post_image'>
</div>
<div class='form-group'>
    <label for='post_content'>Content:</label>
    <textarea class='form-control' name='post_content' id='post_content' placeholder='Type content here...'></textarea>
</div>
<div class='form-group'>
    <label for='post_labels'>Labels:</label>
    <input type='text' class='form-control' name='post_labels' id='post_labels' placeholder='Type label/ labels here, separate labels by comma...'>
</div>
<div class='form-group'>
    <button class='btn btn-success' type='button' id='create_post'>Submit</button>
</div>

The CodeIgniter validation_errors() return this: 'You did not select a file to upload.' I've been working on this for two days, please help.

  • 写回答

1条回答 默认 最新

  • dsa88885555 2015-03-10 08:44
    关注

    You can use FormData without a form element:

    var data = new FormData();
    // append your file
    data.append('file', $('#post_image').files[0]);
    /*
        data.append(...
    */
    jQuery.ajax({
        url: './create/process_create',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data){
            // action on success
        });
    
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)