【问题标题】:Send file from AJAX and retreive from PHP从 AJAX 发送文件并从 PHP 检索
【发布时间】:2020-08-13 19:07:20
【问题描述】:

我有一个表单,我在其中使用 ajax 检索字段并将它们作为 post 发送到 PHP 文件。但其中一个字段是 input type="file"

我的问题如下:如何通过 ajax 将该文件(图像)正确发送到 PHP 文件并读取该文件,以便将其上传到服务器。

这是我的代码: 表单和字段

<form class="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data">
                                    <div class="response" id="response"></div>
                                    <div class="custom-file">
                                        <input type="hidden"
                                               name="<?php echo ini_get("session.upload_progress.name"); ?>"
                                               value="video_upload">
                                        <input type="file" name="lien_video" class="custom-file-input" id="customFile">
                                        <label class="custom-file-label" for="customFile">Choisir le logo</label>
                                    </div>
                                    <div class='progress' id="progress_div">
                                        <div class='bar' id='bar1'></div>
                                        <div class='percent' id='percent1'>0%</div>
                                    </div>
...and some other stuffs

目前为止的脚本 它与表单位于同一个 PHP 文件中

<script type="text/javascript">
            $(document).ready(function () {
                //upload data
                $(document).on('click', '#enreg_ecole', function () {
                    let nom_ecole = $('#input-1').val();
                    let adresse = $('#input-2').val();
                    let nom_rep = $('#input-3').val();
                    let email_rep = $('#input-4').val();
                    let tel_rep = $('#input-5').val();
                    let poste = $('#input-6').val();
                    // let logo = $('#customFile').val();
                    let logo = document.getElementById("customFile").files[0];

                    var form = new FormData();
                    form.append('enreg_ecole', 1);
                    form.append('nom_ecole', nom_ecole);
                    form.append('adresse', adresse);
                    form.append('nom_rep', nom_rep);
                    form.append('email_rep', email_rep);
                    form.append('tel_rep', tel_rep);
                    form.append('poste', poste);
                    if(logo != null){
                        form.append('logo', logo);
                    }


                    $('#scroller').animate({scrollTop: 0}, 'fast');

                    var bar = $('#bar');
                    var percent = $('#percent');

                    $.ajax({
                        url: 'methods/enregistrer_ecole.php',
                        type: 'post',
                        cache: false,
                        contentType: false,
                        processData: false,
                        data:form,
                        enctype: 'multipart/form-data',
                        dataType: 'json',
                        beforeSubmit: function () {
                            document.getElementById("progress_div").style.display = "block";
                            var percentVal = '0%';
                            bar.width(percentVal)
                            percent.html(percentVal);
                        },
                        uploadProgress: function (event, position, total, percentComplete) {
                            var percentVal = percentComplete + '%';
                            bar.width(percentVal)
                            percent.html(percentVal);
                        },
                        success: function (response) {
                            let status = response['status'];
                            let message = response['message'];

                            if (status === 'error') {
                                // window.alert(message);
                                document.getElementById("progress_div").style.display = "none";
                                document.getElementById("alert_div").style.display = "inline";
                                $('#alert_div').addClass('alert-danger');
                                $('#alert_title').html(status);
                                $('#alert_message').html(message +' ' +logo);
                            } else {
                                // window.alert(message);
                                document.getElementById("alert_div").style.display = "inline";
                                // $('#bar1').animate({width: "100%"}, 100);
                                var percentVal = '100%';
                                bar.width(percentVal)
                                percent.html(percentVal);
                                $('#alert_div').addClass('alert-success');
                                $('#alert_title').html(status);
                                $('#alert_message').html(message);
                            }
                        },
                        // complete: function (xhr) {
                        //
                        // },
                        error: function (error, ajaxOptions, thrownError) {
                            // let error = JSON.parse(response);
                            // window.alert('Error happenned: ' + error);
                            // window.alert('Error happenned: ' + response.msg);
                            // var msg = $.parseJSON(error).msg;
                            window.alert(error);
                            window.alert(ajaxOptions);
                            window.alert(thrownError);
                        }
                    });

                    //window.alert('clicked');
                });
            });
        </script>

我希望能够做类似的事情:

$target_file = $target_dir . basename($_FILES["lien_video"]["name"]);

----编辑---- 好的,我尝试了更多代码,它看起来像我的 PHP 文件(从 ajax 调用的 enregistrer_ecole.php),如果我尝试只从表单中检索文本,没关系。如果我尝试只检索文件,那没关系。但试图同时检索文本和图片文件(如 $_POST['someText']$_POST['someFile']['tmp_name'] 它会抛出一个错误。

有人知道正确执行此操作的方法吗?就像先获取文本然后获取文件一样。 我不知道

【问题讨论】:

标签: javascript php mysql ajax


【解决方案1】:

HTML

<div class="container">
    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <div class='preview'>
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>

PHP

<?php

/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);

/* Valid Extensions */
$valid_extensions = array("jpg","jpeg","png");
/* Check file extension */
if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
   $uploadOk = 0;
}

if($uploadOk == 0){
   echo 0;
}else{
   /* Upload file */
   if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
      echo $location;
   }else{
      echo 0;
   }
}

【讨论】:

    【解决方案2】:

    您的 HTML 中缺少一个表单属性,即 enctype

    <form class="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data">
    </form>
    

    还有一个改进:不用将每个输入字段附加到表单数据对象中,您可以编写单行。

    你可以替换所有这些行

    var form = new FormData();
    form.append('enreg_ecole', 1);
    form.append('nom_ecole', nom_ecole);
    form.append('adresse', adresse);
    

    成一行如下:

    var form = new FormData($("form")[0]);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      相关资源
      最近更新 更多