0

I am trying to implement an image upload function on our webplattform. Currently i am getting the Error "You did not select a file to upload". It must work without submit, cause i dont want to refresh the page, and submit buttons will trigger other basic plattoform functions.

My Form:

<div id="selectMotiv">
  <?php echo form_open_multipart('upload/image');?>
   <input type="file" accept="image/*" id="motivImage" name="motivImage"/>              
   <button class="btn btn-outline-primary" id="buMotivUpload" type="submit">Upload</button>
  <?php echo form_close(); ?>
  <div id="uploaded_image">  
  </div> 
 </div>

My js:

$("#buMotivUpload").click(function (e) {
//$('form').on('submit', function (e)) {
  //e.preventDefault();
  console.log($('#motivImage').val());
  var upload_image = $('#motivImage').val();
  if ($('#motivImage').val() == ''){
    alert("Please Select the File");
  } else {
    console.log(upload_image);
    $.ajax({
      url: 'apps/upload',
      method: "POST",
      data: upload_image,
      contentType: false,
      datatype: "json",
      cache: false,
      processData: false,
      success: function (data){
        $('#uploaded_image').html(data);
      }
    });
  }
});

My controller:

<?php

  defined('BASEPATH') OR exit('No direct script access allowed');

  class Upload extends CI_Controller {

  public function index() {  

    $data = $_POST;

    if(isset($_FILES["motivImage"]["name"])){  
      $config = array(
        'upload_path' => "./uploads/",
        'allowed_types' => "gif|jpg|png|jpeg",
        'overwrite' => TRUE,
        'max_size' => "2048000" // Can be set to particular file size , here it is 2 MB(2048 Kb)
        //'max_height' => "768",
        // 'max_width' => "1024"
      );
      $this->load->library('upload', $config);      

      if($this->upload->do_upload('motivImage')){
        $data = $this->upload->data();
        echo 'success';
        //$this->load->view('upload_success',$data);
      }else{        
        echo $this->upload->display_errors(); 
        //$this->load->view('custom_view', $error);
      }   
    }else{
      echo json_encode($data);
    }
  }
}
Phapul
  • 1
  • Related: https://stackoverflow.com/q/166221/1531971 –  Sep 26 '18 at 15:42
  • Possible duplicate of [How can I upload files asynchronously?](https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) – Alex Sep 27 '18 at 00:59
  • need to use `FormData` or plugin to upload via ajax – Alex Sep 27 '18 at 01:00
  • Take a look at similar question [here](https://stackoverflow.com/questions/41585537/upload-image-using-codeigniter-with-ajax-and-formdata) – Pyae Phyo Aung Sep 27 '18 at 03:09

0 Answers0