【问题标题】:How to upload file and insert data with php jquery ajax如何使用 php jquery ajax 上传文件和插入数据
【发布时间】:2018-05-30 09:58:41
【问题描述】:

我无法通过 ajax 发送到 php 文件上传和使用 ajax 的数据。 This my code just send file upload。数据不发送到我的 php 代码。我创建表单并使用 ajax 在 php 上发布点击发送功能。 I'm using codeigniter

这是我的表格:

<form action="<?php echo site_url('home/send_chat');?>" method="post" enctype="multipart/form-data">
  <input name="message" id="message" type="text" class="form-control input-sm" />
  <input type="file" id="file" name="file" />
  <br />
  <span class="input-group btn">
    <button type="submit" class="btn btn-info btn-sm" id="submit">Enkripsi</button>
  </span>
</form>

这个 javascript 使用 ajax 在 php 上发送帖子:

$('#submit').on('click', function(){
  var message = $('#message').val();

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: {fd,message:message},  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});

我已经尝试使用 $_POST['message'];$this-&gt;input-&gt;post("message"); 两者都不起作用 这个 php 来处理代码:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
  public function send_chat()
  {
    $name    = $_FILES['file']['name'];
    $error   = $_FILES['file']['error'];
    $size    = $_FILES['file']['size'];


    // $message = $_POST['message'];
    $message = $this->input->post("message");

    $user    = $this->session->userdata('username');
    $iduser  = $this->session->userdata('userID');



    $insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$userid','$name')";
    $this->db->query($insert);
  }
}

在数据库中,我只是发送名称文件upload.user、消息和iduser,而不是发送。

【问题讨论】:

  • 尽量避免在隐藏字段中发送数据,使用 Session 来实现
  • @kunal 我的消息无法捕获。此消息不是隐藏字段
  • 看到您在隐藏字段中传递用户 ID 和消息,您可以使用身份验证组件或使用会话,您不能直接在隐藏字段中传递用户 ID,任何人都可以更改用户 ID。希望你能理解,这将有助于未来的编码
  • 你有没有在你的函数中打印 $_FILES ??
  • @kunal ok 用户 ID。错了.. 看到这条消息是 type text。 $_FILES 它的工作。但消息不起作用

标签: php jquery ajax codeigniter jquery-file-upload


【解决方案1】:

我认为您的问题可能出在 ajax 代码中 因为您使用的是 formData 对象。尝试用它附加消息变量

$('#submit').on('click', function(){

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);
  fd.append('message ',$('#message').val());

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: fd,  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});

【讨论】:

    【解决方案2】:

    尝试制作这样的 ajax 代码。

      var data = new FormData();
      jQuery.each(jQuery('#file')[0].files, function(i, file) {
        data.append('file', file);
      });
      $.ajax({
        type : "POST",
        url : "<?=base_url()?>home/send_chat",
        data : data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data) {
    
        }
      });
    

    和你的控制器这样对我来说是工作代码

    class Home extends CI_Controller {
    
      function singleImageUpload($upload_name,$folder,$extension,$bnr,$filename)
      {
          if($folder == '')
          {
              $config['upload_path'] = 'images/agent';
          }
          else
          {
              $config['upload_path'] = 'upload/'.$folder."/";
          }
          $config['allowed_types'] = '*';
          if($bnr == 2)
          {
              $config['max_width'] = '3000';
              $config['max_height'] = '3000';
          }
          elseif ($bnr == 1)
          {}
          // $config['file_name'] = $user_name.date('YmdHis').".".$extension;
          $config['file_name'] = $filename;
    
          $this->upload->initialize($config);
          $this->load->library('upload', $config);
          if ( ! $this->upload->do_upload($upload_name))
          {
              $arrayRetutn['upload'] = 'False';
              $arrayRetutn['error'] = $this->upload->display_errors();
          }
          else
          {
              $arrayRetutn['upload'] = 'True';
              $arrayRetutn['data'] = $this->upload->data();
          }
           //echo '<pre>';print_r($arrayRetutn);echo '</pre>'; die;
          return $arrayRetutn;
      }
    
      public function send_chat()
      {
        $user    = $this->input->post("user");
        $message = $this->input->post("message");
        $iduser  = $this->input->post("iduser");
    
        if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '')
        {
            $image_name = explode(".",$_FILES['file']['name']);
            $imgData = $this->singleImageUpload('file','your folder name',$image_name[1],'2',$_FILES['file']['name']);
            if($imgData['upload']=='True')
            {
                $name = $imgData['data']['file_name'];
            }
        }
    
        $insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$iduser','$name')";
        $this->db->query($insert);
      }
    }
    

    【讨论】:

      【解决方案3】:

      我认为@kunal 的意思是您不应该将潜在敏感数据添加为隐藏输入(任何人都可以更改它),而应该在添加到数据库之前直接在您的类中引用这些字段中保存的值。此外,使用嵌入式变量会打开您的应用程序进行 sql 注入,因此请使用准备好的语句。

      <?php 
      
          if ( ! defined('BASEPATH')) exit('No direct script access allowed');
      
      
          class Home extends CI_Controller {
            public function send_chat(){
              $name    = $_FILES['file']['name'];
              $error   = $_FILES['file']['error'];
              $size    = $_FILES['file']['size'];
      
              $user    = $this->session->userdata('username');
              $iduser  = $this->session->userdata('userID');
              $message = $this->input->post("message");
      
      
              $sql="insert into `chat` ( `user`, `message`, `id_user` ,`fileupload` ) values (?,?,?,?)";
              $stmt=$this->db->prepare( $sql );
              if( $stmt ){
                  $stmt->bind_param('ssss',$user,$message,$userid,$name);
                  $stmt->execute();
              }
            }
          }
      

      我玩弄了你原来的 javascript/jQuery 代码,但无法让函数工作(我不使用 jQuery,所以我在猜测)但是使用常规的 vanilla javascript 你可以这样做 ~ php 的部分顶部的代码并不真正相关,因为您会将 ajax 请求发送到 home/send_chat

      <?php
          if( $_SERVER['REQUEST_METHOD']=='POST' ){
              ob_clean();
              /* send some sort of response...    */
              echo json_encode( $_POST );
      
              exit();
          }
      ?>
      <!doctype html>
      <html>
          <head>
              <meta charset='utf-8' />
              <title>xhr upload - no jquery</title>
              <script>
                  document.addEventListener('DOMContentLoaded',function(){
      
                      var callback=function( data ){
                          alert( data )
                      }
      
                      document.getElementById('submit').onclick=function(e){
                          e.preventDefault();
                          var url='<?php echo site_url('home/send_chat');?>';
      
                          var _file=document.querySelector('input[type="file"]');
                          var _form=document.querySelector('form[id="usr-upload"]');
      
                          var xhr = new XMLHttpRequest();
                          var fd=new FormData( _form );
                              fd.append('file', _file.files[0]);
      
                          xhr.onreadystatechange=function(){
                              if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response );
                          };
                          xhr.onerror=function(err){
                              alert(err);
                          };
                          xhr.open('POST',url,true);
                          xhr.send( fd );
                      };
                  },false );
              </script>
          </head>
          <body>
              <form id='usr-upload' method='post' enctype='multipart/form-data'>
                <input name='message' type='text' />
                <input type='file' name='usrfile' />
                <br />
                <span class='input-group btn'>
                  <input type='button' value='Enkripsi' id='submit' />
                </span>
              </form>
          </body>
      </html>
      

      【讨论】:

      • 我已经编辑了我的问题。我的消息仍然没有发送。请问我的问题:(
      【解决方案4】:

      使用 ajax 提交所有带或不带文件的数据

      <form method="post" action="" enctype="multipart/form-data" id="form"/>
         // your own input fields
      </form>
      
      $("#form").submit(function (event) {
       event.preventDefault();
       //tinyMCE.triggerSave();
      $.ajax({
          url: "<?php echo base_url('your_own_controller/your_own_method'); ?>",
          type: "post",
          data: new FormData(this),
          processData: false,
          contentType: false,
          cache: false,
          async: false,
      
          beforeSend: function () {}, //if you like to do something before submit
          complete: function () {}, //if you like to do something before submit 
      
          success: function (response) {
           //check response and do some your own stuff
          };
      });
      

      【讨论】:

        猜你喜欢
        • 2015-09-15
        • 2011-07-13
        • 2017-02-15
        • 1970-01-01
        • 2014-07-05
        • 1970-01-01
        • 2021-09-09
        相关资源
        最近更新 更多