Gardezi
Gardezi

Reputation: 2842

Upload File Using Ajax in Codeigniter

I am trying to upload a file with some other data. The thing is I'm getting the error that You did not select a file to upload. I can't understand what is it that I'm doing wrong. I would be really glad if anybody can point out what is it that I am doing wrong. Thanks

html file

 <div class="modal-body">
          <form id="add_message" enctype="multipart/form-data"  method="post" action="<?php echo base_url() ?>apps/messages/composeMessage">

            <div class="form-group">
              <select id="messageTo" class="form-control" data-plugin="select2" multiple="multiple" data-placeholder="To:" name="messageTo">
              </select>
            </div>

            <div class="form-group">
              <input class="form-control" placeholder="Subject" id="messageSubject" name="messageSubject"></input>
            </div>

            <div class="form-group">
              <textarea  data-provide="markdown" data-iconlibrary="fa" rows="10" id="messageBody" name="messageBody"></textarea>
            </div>

            <input type="hidden" name="fname" value="" id="formName" ></input>

            <div class="left">

                <!-- <span class="btn green fileinput-button"> -->

                    <input id="message_attachement" type="file" name="file_attac" size="20" >
                <!-- </span> -->
            </div>
            <!-- <button class="btn btn-primary"  type="submit" value="submit">Send</button> -->
          </form>
        </div>
        <div class="modal-footer text-left">
          <button class="btn btn-primary" data-dismiss="modal"  id="addformButton">Send</button>
          <button class="btn btn-primary" data-dismiss="modal"  id="saveformButton">Save</button>
          <a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Cancel</a>
        </div>

JS

$("#addformButton").on('click' , function(){
    debugger;       
        $.ajax({
            type: "POST", 
            url: base_url + "apps/messages/composeMessage",
            async: false,
             mimeType: "multipart/form-data",
            dataType:JSON, 
            data:{
                'reciever': $('#messageTo').val() , 
                'subject': $('#messageSubject').val(),
                'text': $('#messageBody').val(),
                'type': 'active',
                'msgId': $('#formName').val(),
                'attachment' : $('#message_attachement').val()
            },
            success: function(response){
            },
            error: function(response){
            }
        });
    });

Controller

 $this->load->helper('file_upload');
         $filename = $this->input->post('attachment');
          $path = 'uploads/attachments/';
          $allowed_types = 'erb|php|txt';
          $redirect = '';
          // error_log("outside");
          if (!empty($this->input->post('attachment'))) {
              // error_log("inside");
              // error_log ("Parameters: " . $path." Types: ". $allowed_types." name: ". $filename." redirect: ". $redirect);
              $parameters['profile_pic'] = file_upload($path, $allowed_types, $filename, $redirect);
              // error_log("The path is ");
              // error_log($parameters['profile_pic']);
              if ($this->session->set_userdata("img_errors")) {
                // error_log("error");
                return false;
              }
          }

File Upload function

  function file_upload($upload_path , $allowed_types , $filename , $redirect)
  {
      $ci = & get_instance();

      $config['upload_path'] = $upload_path;
      $config['allowed_types'] = $allowed_types;
      // $config['max_size'] = 1024;//1mb
      // $config['max_width'] = 1024;
      // $config['max_height'] = 1024;

      $ci->load->library('upload', $config);
      $data = NULL;
      if (!$ci->upload->do_upload($filename)) {
        error_log("within the file");
//          $error = array('error' => $ci->upload->display_errors());
        error_log($ci->upload->display_errors());
          $ci->session->set_userdata('img_errors', $ci->upload->display_errors());
          //error_log(print_r($ci->upload->display_errors(),true));
          // redirect(base_url() . $redirect);
      } else {
        error_log("uploading");
          $data = array('upload_data' => $ci->upload->data());
          // do_resize($config['upload_path'] , $data['upload_data']['file_name']);
      }

      return $config['upload_path'] . $data['upload_data']['file_name'];
  }

Upvotes: 0

Views: 1994

Answers (2)

Gardezi
Gardezi

Reputation: 2842

Just found out I had not posted the solution that helped me for this problem. Here's what I did

The real problem was with sending the file to the server. I just needed to set the cache, processData and contentType to false and that worked for me.

and one more thing I needed to send data to the server using form data.

I have posted the relevant code that helped me sending data to the server. Hope it helps

    var form = $('#add_message')[0]; // standard javascript object here
    var formData = new FormData( $('#add_message')[0]);
    $.ajax({
        type: "POST", 
        url: base_url + "apps/messages/composeMessage",
        cache: false,
        contentType: false,
        processData: false,
        data: formData,
        success: function(response){
          // some action on success
        }, 
        error: function(response){
          // some action on error 
        }
    });

Upvotes: 0

Faisal Ashfaq
Faisal Ashfaq

Reputation: 2678

This is the working code I used in my most recent project, the code is self explanatory however feel free to ask any question.

HTML:

                <form action="http://localhost/index.php/upload_file" method="post" style="display:none;" id="file_upload_form" enctype="multipart/form-data">
                    <input type="file" id="dialog_triggerer" name="uploaded_file">
                </form>

                <button class="btn btn-default btn-fab-sm" id="file_attach">
                    <span class="mdi-file-attachment"></span>
                </button>

JS:

trigger this code on some action:

            var form = $('form')[0]; // standard javascript object here
            var formData = new FormData(form);

            if($("#dialog_triggerer").val()!=""){

                $.ajax( {
                  url: FRONTEND_URL + '/upload_file',
                  type: 'POST',
                  data: formData,
                  processData: false,
                  contentType: false,
                  async: false
                } ).done(function(data){
                    file_data = JSON.parse(data);
                    new_post.file_data = file_data;
                }); 

            }

upload_file ctrl:

<?php

class Upload_file extends CI_Controller{
    public function __construct(){
        parent::__construct();
    }

    public function index(){

        $valid_file=true;
        $message;


        //if they DID upload a file...
        if($_FILES['uploaded_file']['name'])
        {
            //if no errors...
            if(!$_FILES['uploaded_file']['error'])
            {
                //now is the time to modify the future file name and validate the file
                $new_file_name = strtolower($_FILES['uploaded_file']['name']); //rename file
                if($_FILES['uploaded_file']['size'] > (20024000)) //can't be larger than 20 MB
                {
                    $valid_file = false;
                    $message = 'Oops!  Your file\'s size is to large.';
                }

                //if the file has passed the test
                if($valid_file)
                {
                    $file_path = 'themes/uploads/'.$new_file_name;
                    move_uploaded_file($_FILES['uploaded_file']['tmp_name'], FCPATH . $file_path);
                    $message = 'Congratulations!  Your file was accepted.';
                }
            }
            //if there is an error...
            else
            {
                //set that to be the returned message
                $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['uploaded_file']['error'];
            }
        }
        $save_path = base_url().$file_path;

        $name = $_FILES['uploaded_file']['name'];
        $size = $_FILES['uploaded_file']['size'];
        $type = $_FILES['uploaded_file']['type'];


        $data = array(
            "message" => $message,
            "save" => $save_path,
            "name" => $name,
            "size" => $size,
            "type" => $type
        );

        $this->load->view('upload_file/upload_file.php', $data);


    }
}

upload_file.php view:

<?php

$res = array(
    "msg" => $message,
    "path" => $save,
    "name" => $name,
    "size" => $size,
    "type" => $type
);

echo json_encode($res);



?>

Upvotes: 1

Related Questions