Uploading a file in CodeIgniter PHP Using Ajax And jQuery

倾然丶 夕夏残阳落幕 提交于 2019-12-13 21:53:22

问题


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:


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


来源:https://stackoverflow.com/questions/28958745/uploading-a-file-in-codeigniter-php-using-ajax-and-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!