使用AJAX和PHP上传文件

时间:2014-03-24 15:44:20

标签: php jquery ajax file-upload

我试图创建一个脚本来将文件上传到我的服务器。

真正困扰我的是,虽然文件未上传,但仍会执行成功通话。

HTML

<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
     <label>Castellà</label><input name="mapa_es" id="mapa_es" type="file" />
        <div id="progressbox_es" style="display:none;">
             <div id="progressbar_es">
                  <div id="statustxt_es">0%
                  </div>
             </div>
       </div>
</form>

JS

$(document).ready(function() {
                $('#mapa_es').change(function() {
                    var formData = (this.files[0]);
                    $.ajax({
                        xhr: function()
                        {
                            var xhr = new window.XMLHttpRequest();
                            xhr.upload.addEventListener("progress", function(evt) {
                                if (evt.lengthComputable) {
                                    var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
                                    console.log(percentComplete + '%');
                                    //Progress bar
                                    $('#progressbox_es').show();
                                    $('#progressbar_es').width(percentComplete + '%')
                                    $('#progressbar_es').css('background-color', '#6699FF');
                                    $('#statustxt_es').html(percentComplete + '%');
                                    if (percentComplete > 50)
                                    {
                                        $('#statustxt_es').css('color', '#000');
                                    }
                                }
                            }, false);
                            xhr.addEventListener("progress", function(evt) {
                                if (evt.lengthComputable) {
                                    var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
                                    //Progress bar
                                    $('#progressbox_es').show();
                                    $('#progressbar_es').width(percentComplete + '%');
                                    $('#progressbar_es').css('background-color', '#6699FF');
                                    $('#statustxt_es').html(percentComplete + '%');
                                    if (percentComplete > 50)
                                    {
                                        $('#statustxt_es').css('color', '#000');
                                    }
                                    console.log(percentComplete + '%');
                                }
                            }, false);
                            return xhr;
                        },
                        url: 'processupload.php',
                        type: 'POST',
                        data: formData,
                        async: true,
                        beforeSend: function() {
                        },
                        success: function(msg) {
                            console.log(msg);
                        },
                        cache: false,
                        contentType: false,
                        processData: false
                    });
                    return false;
                });
            });

和processupload.php中的PHP代码

<?php
if (isset($_FILES["mapa_es"]) && $_FILES["mapa_es"]["error"] == UPLOAD_ERR_OK) {
    $UploadDirectory = 'mapes/';

    if ($_FILES["mapa_es"]["size"] > 5242880) {
        echo "File size is too big!";
    }


    $File_Name = strtolower($_FILES['mapa_es']['name']);
    $File_Ext = substr($File_Name, strrpos($File_Name, '.'));
    $Random_Number = rand(0, 9999999999);
    $NewFileName = $Random_Number . $File_Ext;

    if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
        echo 'Success! File Uploaded.';
    } else {
        echo 'error uploading File!';
    }
} else {
    echo 'Something wrong with upload!';
}
?>

我将感谢你能给我的任何帮助。感谢。

编辑:我遵循了gtryonp建议,我遇到了更多问题。 当我尝试var_dump($ _ FILES)时,我得到的只是一个空字符串。

我还尝试使用$()提交表单。提交而不是$()。更改并且它有效,我认为这可能是因为&#34; enctype =&#34; multipart / form-data&# 34;在表单标签上。 有没有办法实现它而无需提交整个表格?

1 个答案:

答案 0 :(得分:1)

您的processupload.php以die(消息)结尾,将作为正常程序结束,因此将触发success事件并且console.log(&#39; FILE UPLOADED&#39;)将成为即使在错误的情况下,你的反应总是如此使用 echo消息更改所有 die(消息),例如:

if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded to '.$UploadDirectory . $NewFileName;
} else {
echo 'error uploading File!';
}
...

并更改成功功能以回应可能的屏幕答案。类似的东西:

success: function(msg) {
console.log(msg);
},

HAGD