如何在ajax和codeigniter中发送带有图像的字符串文本

时间:2016-05-27 11:16:54

标签: php jquery ajax codeigniter

我使用ajax和php codeigniter上传Image。现在我想发布一些文本字符串,以便我可以将其保存在数据库中。我不知道怎么做。请检查代码,我已经使用ajax

为上传文件编写了代码

Jquery代码

$('#post_button').click(function(event) {
         $('#loadpost').css('display','inline');
        var post_data = $('#post').val();

            // console.log('hit');
            // alert($('input[type=file]').val());
    if($("#fileupload").val() != ''){
        if (typeof FormData !== 'undefined') {

      var form = $('#formname').get(0); 
    var formData = new FormData(form);  
    console.log(formData);
    $.ajax({
      type: "POST",
      url: "Profile/uploadimg",
      data: formData,
      mimeType:"multipart/form-data",
      dataType: 'json',
      xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            return myXhr;
      },
      cache:false,                    
      contentType: false,
      processData: false,
      success: function(result){
       get_post();
       $('#loadpost').css('display','none');
       toastr8.info({
      message:'Your Image Has been Uploaded', 
        title:"New Image Uploaded",
        iconClass: "fa fa-info",
   // imgURI: ["https://unsplash.it/120/120?image=20"]
    });
       //$(".loadpost").hide();
      }                       
    });

     event.preventDefault();

        }  

}

         else {
            var url = "profile/add_post";
            $.ajax({
                type: "POST",
                url: url,
                data: 'post=' + post_data,
                //datatype: "json",
                success: function() {

                    get_post();

                }
            });

            $("#post").val('');
        }
    })
});

我的控制器代码

public function uploadimg()
    {
    $var = $_FILES ['fileUp'];
    $img=$_FILES ['fileUp'];
    $config['upload_path'] = '../virkmusic/images'; 
    $config['overwrite'] = 'TRUE';
    $config["allowed_types"] = 'jpg|jpeg|png|gif';
    $config["max_size"] = '1400';
    $config["max_width"] = '1400';
    $config["max_height"] = '1400';
    $this->load->library('upload', $config);

    if(!$this->upload->do_upload('fileUp')) 
    {               
        $this->data['error'] = $this->upload->display_errors(); 
        echo json_encode(array("result"=>$this->data['error']));
        exit;
    } 
    else 
    { 

            $uname['uname'] =$this->session->all_userdata('uname');
            $post_data = array(
            'id' => '',
            'userid' => '1',
            'posttype' => 'content',
            'sharewith' => 'Friend',
            'username' => $uname['uname']['uname'] ,
            'picture'=>$var['name'],
            'postcontent' => $this->input->post('post'),
            'postdate' => date("Y-m-d H:i:s"),
            'isactive' => '1'
           );
          $this->Profile_model->insert_post_to_db($post_data);
          echo json_encode(array("result"=>"Success"));
          exit;
    }

如何使用图像发送字符串文本以便我可以保存。我想知道这个

由于

1 个答案:

答案 0 :(得分:0)

我正在尝试这一次......

html ---

<form class="reg-page" name="registrationForm" id="registrationForm"   action="#" method="post" enctype="multipart/form-data">

                <div class="col-md-12" style="padding:0px;">
                <div class="form-group col-md-4" style="padding:0px;">
                <label>First Name <span class="color-red">*</span></label>
                <input type="text" required id="fname" name= "first_name" class="form-control margin-bottom-20">
                </div>
                <div class="form-group col-md-4">
                <label>Middle Name </label>
                <input type="text" id= "mname" name = "mid_name" class="form-control margin-bottom-20">
                </div>
                <div class="form-group col-md-4">
                <label>Last Name <span class="color-red">*</span></label>
                <input type="text" required id= "lname" name = "last_name" class="form-control margin-bottom-20">
                </div>

                <div class="form-group">
                <label>Profile<span class="color-red">*</span></label>
                <input type="file" name="file" id = "inputfile"  required   class="margin-bottom-20">
                </div>
                <hr>

                <div class="row">
                    <div class="col-lg-6 text-right">
                        <button class="btn-u" id ="registerBtn" value= "submit" type="submit">Register</button>                        
                    </div>
                </div>
            </form>

<强>的Jquery ---

$(document).ready(function() {
    $("form#registrationForm").submit(function()
         var formData = new FormData($(this)[0]);
         $.ajax({
         url: 'auth/register',
         type: 'POST',
         data: formData,
         async: false,
         success: function(msg) {
         //To do after successfull registration
         },
         error: function(data){
          //To do try again
         },
         cache: false,
         contentType: false,
         processData: false
    });
    return false;
    });
});

控制器---

        $config['upload_path']  = $path;
        $config['allowed_types'] = '*';
        $config['overwrite'] = TRUE;
        $config['remove_spaces'] = FALSE;
        $this->load->library('upload', $config);
        $filedata;
        if ( ! $this->upload->do_upload('file'))
        {
            $arr = array (
                    'error' => true,
                    'message' => "Register failed . Please upload only pdf or doc files." 
            );
            echo json_encode ( $arr );
            exit ();
        }
        else
        {
                $filedata = array('upload_data' => $this->upload->data());
        }