使用带有ajax和formdata的codeigniter上传图像

时间:2017-01-11 08:00:22

标签: php jquery ajax codeigniter file-upload

我喜欢使用带有JQuery AJAX的PHP中的codeigniter Framework上传图像,而无需重定向页面。当我上传图像时,它会重定向到控制器区域并且值不会插入到数据库中,ajax响应也不会出现,

任何人都可以解决我的问题....提前致谢...

这是我的观看区域。

<form  action="<?php echo site_url("Admin_Creator/do_upload")?>" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="frm_imageuupload"  method="post">
               <div class="form-group">
               <label for="menu">Select Menu</label>
                   <select class="form-control" id="selectmenuid">
                    <option value="">-- Select Menu --</option>
                    <?php foreach($showData as $show):?>
                      <option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
                    <?php endforeach;?>
                    </select>
                </div>
               <div class="form-group">
               <label for="menu">Select Sub Menu</label>
                   <select class="form-control" id="selectsubmenu">
                       <option>--Select Sub Menu--</option>
                    </select>
               </div>
              <div class="form-group">
                  <label for="imagetitle">Image Title</label>
                  <input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
                </div>
               <div class="control-group form-group">
                        <div class="controls">
                            <label>Upload Photo:</label>
                            <input name="file" type="file" id="image_file" required>
                            <p class="help-block"></p>
                        </div>
               </div>
               <button type="submit" class="btn btn-primary" id="submit">Submit</button>
           </form>

这是我的Ajax编码

$('#submit').on('click',function(){
        var inputFile=$('input[name=file]');
        var fileToUpload=inputFile[0].files[0];
        var other_data = $('#frm_imageuupload').serializeArray();
        var formdata=new FormData();
        formdata.append(fileToUpload);
        formdata.append(other_data);
         //now upload the file using ajax
         $.ajax({
             url:"<?php echo base_url('Admin_Creator/do_upload') ?>",
             type:"post",
             data:formdata,
             processData:false,
             contentType:false,
              success: function(data){
            if (data== 'true'){   
               window.location.reload();
            }
            else{
               alert("Pls Try Again");
            }
           }
         });

这是我的控制器编码......

 public function do_upload(){
        $config['upload_path']="./upload";
        $config['allowed_types']='gif|jpg|png';
        $this->load->library('upload',$config);
        if($this->upload->do_upload()){
        $data = array('upload_data' => $this->upload->data());
        $data1 = array(
        'menu_id' => $this->input->post('selectmenuid'),
        'submenu_id' => $this->input->post('selectsubmenu'),
        'imagetitle' => $this->input->post('imagetitle'),
        'imgpath' => $data['upload_data']['file_name']
        );  
        $result= $this->Admin_model->save_imagepath($data1);
        if ($result == TRUE) {
            echo "true";
        }
        }

     }

这是我的模型编码

public function save_imagepath($data1)
    {
        $this->db->insert('images', $data1);
         return $this->db->insert_id();
    }

3 个答案:

答案 0 :(得分:3)

试一试。它正在工作 -
HTML表单 -

<form enctype="multipart/form-data" id="submit">
               <div class="form-group">
               <label for="menu">Select Menu</label>
                   <select class="form-control" name="selectmenuid" id="selectmenuid">
                    <option value="">-- Select Menu --</option>
                    <?php foreach($showData as $show):?>
                      <option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
                    <?php endforeach;?>
                    </select>
                </div>
               <div class="form-group">
               <label for="menu">Select Sub Menu</label>
                   <select class="form-control" name="selectsubmenu" id="selectsubmenu">
                       <option>--Select Sub Menu--</option>
                    </select>
               </div>
              <div class="form-group">
                  <label for="imagetitle">Image Title</label>
                  <input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
                </div>
               <div class="control-group form-group">
                        <div class="controls">
                            <label>Upload Photo:</label>
                            <input name="file" type="file"  id="image_file" required>
                            <p class="help-block"></p>
                        </div>
               </div>
               <button type="submit" class="btn btn-primary" id="sub">Submit</button>
           </form>  

Ajax -

$('#submit').submit(function(e){
    e.preventDefault(); 
         $.ajax({
             url:'Your path',
             type:"post",
             data:new FormData(this),
             processData:false,
             contentType:false,
             cache:false,
             async:false,
              success: function(data){
                  alert(data);
           }
         });
    });  

只需在ajax中设置url,它就能完美运行 控制器功能 -

public function do_upload(){
        $config['upload_path']="./upload";
        $config['allowed_types']='gif|jpg|png';
        $this->load->library('upload',$config);
        if($this->upload->do_upload("file")){
        $data = array('upload_data' => $this->upload->data());
        $data1 = array(
        'menu_id' => $this->input->post('selectmenuid'),
        'submenu_id' => $this->input->post('selectsubmenu'),
        'imagetitle' => $this->input->post('imagetitle'),
        'imgpath' => $data['upload_data']['file_name']
        );  
        $result= $this->Admin_model->save_imagepath($data1);
        if ($result == TRUE) {
            echo "true";
        }
        }

     }

答案 1 :(得分:0)

这很简单。
问题是ajax
你应该先停止表格提交

$('form').on('submit',function(e){//bind event on form submit.
   e.preventDefault();//stop submit
   .........          //your other codes

答案 2 :(得分:0)

这就是我解决这个问题的方法

<强> HTML     

      <div class="form-group">
                <label for="logo">Service Provider Logo / Icon</label>
                <input type="file" class="form-control" name="file" id="file" required="required">
                <img src="#" id="img-logo"  alt="image" class="img-responsive" style="height: 200px !important;">
                <input type="hidden" class="" id="returned-sp-id">
            </div>
            <div class="form-group">
                <label for="caption">Service Provider Name</label>
                <input type="text" class="form-control" id="caption" required="required">
            </div>
            <div class="form-group">
                <label for="details">Service Provider Details</label>
                <textarea type="text" class="form-control" id="details" required="required"></textarea>
            </div>
    </form>

Jquery Ajax

      $(function() {
          $('#service-provider-details').on('submit', function(e){
              var caption = $('#caption').val();
              var details = $('#details').val();

              var data = new FormData(this);
              data.append('caption', caption);
              data.append('details', details);

              $.ajax({
                 url:'<?= base_url(), 'create_profile_sp/upload' ?>',
                 type:"post",
                 data: data,
                 processData:false,
                 contentType:false,
                 cache:false,
                 async:true,
                 success: function(data){
                   console.log(data);
                 }
               });
               e.preventDefault();
          });
      });

控制器

      class Create_profile_sp extends CI_Controller
      {

        function __construct()
        {
           parent::__construct();
           $this->load->model('profile_sp_m');
        }

        public function upload($data) {
           $data = $_POST;
           $this->profile_sp_m->upload_logo($data);
        }
     }

模型

     class profile_sp_m extends CI_Model
     {
        public $_tablename = 'profiles';

        function __construct()
        {
          // Call the Model constructor
          parent::__construct();
        }

        public function upload_logo($data) {

            $caption = $data['caption'];
            $details = $data['details'];

            if(isset($_FILES["file"]["type"]))
            {
              $validextensions = array("jpeg", "jpg", "png");
              $temporary = explode(".", $_FILES["file"]["name"]);
              $file_extension = end($temporary);

              if ((($_FILES["file"]["type"] == "image/png") ||($_FILES["file"]["type"] == "image/jpg") || 
                 ($_FILES["file"]["type"] == "image/jpeg") ) && 
                 ($_FILES["file"]["size"] < 100000) && 
                  in_array($file_extension, $validextensions)){
                 if ($_FILES["file"]["error"] > 0)
                  {
                      echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
                  } else {
                    $sourcePath = $_FILES['file']['tmp_name']; Store source path in a variable
                    $targetPath = "uploads/profiles/" . $_FILES['file']['name']; // The Target path where file is to be stored
                    move_uploaded_file($sourcePath,$targetPath); // Moving Uploaded file
                     // The Image Data
                     $imageData = [
                         'caption'   => $caption,
                         'description'   => $details,
                     ];

                     // Insert the data
                     $this->db->insert($this->_tablename, $imageData);
                  }
              }
           }

        }



     }