简体   繁体   English

使用AJAX和PHP上传文件

[英]Upload a file using AJAX and PHP

I'm trying to make a script to upload files to my server. 我正在尝试制作一个脚本来将文件上传到我的服务器。

What's really bothering me is that the success call is executed though the file is not uploaded. 真正令我困扰的是,尽管未上传文件,但执行了成功调用。

HTML 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 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;
                });
            });

and the PHP code in processupload.php 以及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!';
}
?>

I will appreciate any help you could give me. 我会很感激您能给我的任何帮助。 Thanks. 谢谢。

EDIT: I followed gtryonp suggestions and I got into more problems. 编辑:我遵循gtryonp建议,我陷入了更多问题。 When I try to var_dump($_FILES) all I get is an empty string. 当我尝试var_dump($ _ FILES)时,我得到的只是一个空字符串。

I also tried to submit the form using $().submit instead on $().change and it worked, I think it may be because of "enctype="multipart/form-data" on the form tag. Is there any way to achieve it without having to submit the whole form? 我也尝试使用$()。submit而不是$()。change来提交表单,并且它起作用了,我认为这可能是因为form标记上的“ enctype =“ multipart / form-data”。无需提交整个表格即可实现?

Your processupload.php is ending with a die(message) and will be take as a normal program end, so the success event will be fired and the console.log('FILE UPLOADED') will be your response always, even in error cases. 您的processupload.php以die(message)结尾,将被视为正常程序结束,因此将触发成功事件,并且console.log('FILE UPLOADED')将始终是您的响应,即使在错误情况下也是如此。 Change all your die(message) with echo message , something like: 使用echo message更改所有的die(message) ,例如:

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

and change the success function for something that echoes the possible answers to your screen. 并将成功功能更改为与屏幕上可能的答案相呼应的功能。 Something like: 就像是:

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

HAGD HAGD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM