使用AJAX将头像上传到服务器

时间:2016-02-16 23:59:32

标签: javascript php jquery ajax file-upload

我已经研究了最好的方法,并在各种演示中不断收集相互矛盾的信息和建议。

我的代码如下......

HTML

<img src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
        <p><a href="#" onclick="$('#avatar-uploader').trigger('click'); return false;">Change</a><span class="pull-right">Powered by Gravatar</span></p>
        <input type="file" name="avatar-uploader" id="avatar-uploader" style="display: none;" />

的javascript

$('input[type=file]').on('change', function(){
    $.ajax({
        url: "/ajax/upload-new-avatar.ajax.php", // Url to which the request is send
        type: "POST",             // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(data)   // A function to be called if request succeeds
        {
        alert("Success");
        }
        });
});

PHP:/ajax/upload-new-avatar.ajax.php

error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$sourcePath = $_FILES['avatar-uploader']['tmp_name'];       // Storing source path of the file in a variable
$targetPath = "".$_FILES['avatar-uploader']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file

我确信这里有一些简单的东西,我在这里会觉得非常愚蠢,但是有人可以向我解释为什么图像没有被上传到服务器并保存在AJAX目录中进一步处理。

我需要做的是当用户点击图像下方的“更改”超链接时,它会打开文件上传对话框(正常工作),一旦选择了图像,它就会通过AJAX连接自动上传到服务器(可能正常工作,日志显示正在触发PHP文件),然后图像文件需要保存在AJAX目录中,以便稍后在代码中进一步处理,以便将其上传到头像服务。

提前致谢。

1 个答案:

答案 0 :(得分:1)

设法让它运转起来......

这是我修改过的代码......

的Javascript

$('input[type=file]').on('change', function(event){
    files = event.target.files;
    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening
    $("#avatar-status").text("Loading new avatar...");
    $("#avatar").css("opacity", "0.4");
    $("#avatar").css("filter", "alpha(opacity=40);");
    //Create a formdata object and add the files
    var data = new FormData();
    $.each(files, function(key, value) {
        data.append(key, value);
    });
    $.ajax({
        url: '/ajax/upload-new-avatar.ajax.php?files',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR) {
            if(typeof data.error === 'undefined') {
                //Success so call function to process the form
                //submitForm(event, data);
                $("#avatar-status").text("Powered by Gravatar");
                $("#avatar").css("opacity", "");
                $("#avatar").css("filter", "");
            } else {
                //Handle errors here
                alert('ERRORS: ' + textStatus);
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            //Handle errors here
            alert('ERRORS: ' + textStatus);

        }
    });
});

PHP

session_start();
require_once("../libraries/logging.lib.php");
new LogEntry("AJAX Upload Started - UploadNewAvatar", Log::DEBUG, "AvatarUpload");
sleep(3);
$data = array();
if(isset($_GET['files'])) {  
    $error = false;
    $files = array();
    $uploaddir = '../tmp/';
    foreach($_FILES as $file) {
        if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name']))) {
            $files[] = $uploaddir .$file['name'];
            new LogEntry("UploadNewAvatar - Upload Successful", Log::DEBUG, "AvatarUpload");
        } else {
            $error = true;
            new LogEntry("UploadNewAvatar - Errors Occured", Log::ERROR, "AvatarUpload");
        }
    }
    $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
    new LogEntry("UploadNewAvatar - Form was submitted successfully", Log::DEBUG, "AvatarUpload");
}
echo json_encode($data);

HTML

<img id="avatar" src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
        <p><a href="#" onclick="$('#upfile').trigger('click'); return false;">Change</a><span id="avatar-status" class="pull-right">Powered by Gravatar</span></p>
        <input type="file" name="upfile" id="upfile" style="display: none;" />