如何使用 php jquery ajax 上传文件和插入数据

How to upload file and insert data with php jquery ajax

我无法通过 ajax 发送到 php 文件上传和数据 ajax。 This my code just send file upload。数据未发送到我的 php 代码。我使用 ajax 创建表单并在单击时发送函数到 php 上的 post。 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 上发送 post:

$('#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->input->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,它没有发送。

尝试编写这样的 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);
  }
}

我认为@kunal 的意思是你不应该将潜在的敏感数据添加为隐藏输入(任何人都可以更改它)但应该在添加之前直接在 class 中引用这些字段中保存的值到数据库。此外,使用嵌入式变量会打开您的应用 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,所以我在猜测),但使用的是普通的普通 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>

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

$('#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);
    }  
  });
});

使用 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
    };
});