【问题标题】:how to passing file and other data form by ajax as a POST object to a php page and save it to database?如何通过ajax将文件和其他数据形式作为POST对象传递到php页面并将其保存到数据库?
【发布时间】:2014-12-24 19:30:37
【问题描述】:
  • 我有一个包含文本数据的表单,我想发送一个表单内容和文件 通过 ajax POST 方法到 Proccess.php 处理程序,我想得到 二进制文件作为对象插入到数据库(mysql)中。
  • 我知道将文件保存到数据库很奇怪,但在这种情况下是必要的。
  • 还有一个问题:为什么 POST 数据在 $_POST 数组中发送,而来自同一页面的 <input type="file" name="file"> 的 $_POST['file'] 未定义?

这是我的代码: PHP handler:(proccess.php 哪个ajax 向这个页面发送数据):

<?php
    $mysqli = new mysqli('localhost', 'root', '', 'msgsys');
    if(mysqli_connect_errno()) {
        print_r("<h4 id='senterror'>Connection Failed: " . mysqli_connect_errno()."</h4>");
        exit();
    }
    $email = $_POST['email'];
    $file = $_FILES['file']['name']; //i'll try to give an object property to sure that the object exists;
    $file2 = $_POST['file']; //the same attemp;
    print_r($file);
    if($stmt = $mysqli -> prepare("SELECT uid FROM user WHERE eaddress=?")) {
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = mysqli_fetch_row($result)) {
            $recUid = $row[0];
        }
        $stmt->close();
        if (!$result || mysqli_num_rows($result) <= 0) {
            print_r("<h4 id='senterror'>You Can not Mailing To Who doesn't exists!</h4>");
            $mysqli->close();
            exit();
        } else {
            date_default_timezone_set('ASIA/Tehran');
            $today = date('m/d/Y-H:i:s');
            $stmt = $mysqli->prepare("INSERT INTO message (sdeltag,rdeltag,rreadtag,timesent,body,subjecttxt,sender,receiver) VALUES ('0','0','0',?,?,?,'1',?)");
            $stmt->bind_param("ssss",$today,$_POST['txt'], $_POST['subject'],$recUid);
            $stmt->execute();
            print_r("<h4 id='mailsent'>Message Sent Successfully!</h4>");
            $stmt->close();
        }
        $mysqli->close();
    }
?>

ajax:

$(document).ready(function () {
        $('#sendmail').submit(function () {
            var that = this;
            $('#response').html("<b>Loading response...</b>");
            $.ajax({
                type: 'POST',
                url: 'proccess.php',
                data: $(that).serialize()
            })
                .done(function (data) {
                    $('#response').html(data);

                })
                .fail(function () {
                    alert("Posting failed.");

                });
            this.reset();
            return false;

        });
    });

【问题讨论】:

  • @Musa 只保留文件,表单数据的其他字段呢?
  • 当您发布文件时,您不会使用 $_POST['file'] 访问它,它会存储在文件的服务器全局变量中:$_FILES['file']
  • @ARH 你读过这个答案了吗stackoverflow.com/a/8758614/1353011
  • @Colum $_FILES['file'] 它说它是未定义的,但我认为所有的表单内容,包含文件,用 ajax 发布到 proccess.php,不是吗?

标签: php jquery mysql ajax asyncfileupload


【解决方案1】:

我将重写 ajax 部分,如下所示,对我来说效果很好:

$(document).ready(function () {
    $('#sendmail').submit(function () {
        var formData = new FormData($('form')[0]);
        $('#response').html("<b>Loading response...</b>");
        $.ajax({
            url: 'proccess.php',  //Server script to process data
            type: 'POST',
            data: formData,
            async: false,
            success: function (msg) {
                $('#response').html(msg);
            },
            cache: false,
            contentType: false,
            processData: false
        });
        this.reset();
        return false;
    });
});

【讨论】:

    【解决方案2】:

    您可以使用此 AJAX 来保存您的字段值。

     $(document).ready(function (e) {
        $("#YourButtonID").on('submit',(function(e) {
        e.preventDefault();
        var fileValue = $('#file').val();
        if(fileValue !='')
        {
            $.ajax({
                url: "submitFile.php", 
                type: "POST",             
                data: new FormData(this), 
                contentType: false,                  
                processData:false,        
                success: function(data)   
                {
                    $("#message").html('Image Uploaded Successfully..!!');
                    $('#ShowImage').show();
                    //$('#file').val('');
                    $('#ShowImage').attr("src",data);
                }
            });
        }
        else
        {
            alert("Please Choose file!");
            return false;
        }
        }));
    
        });
    

    这是 HTML 部分

    <form id="uploadimage" method="post" enctype="multipart/form-data">
       <div id="message"></div><br/>    
       <img src="" id="ShowImage" style="display:none;"><br/><br/>
       <label>File:</label>
       <input type="file" name="file" id="file" /><br/><br/>
       <input type="submit" value="Upload" name="submit" id="submit" />
    </form>
    

    在 PHP 端编写这段代码

    <?php
        if($_FILES["file"] !='')
        {
            $name = strtolower($_FILES['file']['name']);
            $File_Ext = substr($name, strrpos($name, '.')); 
            if($name !='' && $File_Ext !='')
            {       
                $NewFileName = time().$File_Ext;
            }
    
            $cmpltPath = "uploads/".$NewFileName; 
            move_uploaded_file($_FILES['file']['tmp_name'],$cmpltPath) ;
            echo $cmpltPath;
        }
        else
        {
            echo "Failure!!";
        }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多