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

标签 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 目录中,以便稍后在代码中进一步处理,以便上传到头像服务。

提前致谢。

最佳答案

已成功使其正常工作...

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

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;" />

关于javascript - 使用 AJAX 将头像上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35445376/

相关文章:

php - laravel morphTo 如何使用自定义列?

javascript - 使用 jQuery 在图像转换之间跳转

javascript - 如何在调整大小时删除类?

javascript - 我应该如何避免使用 Sinon.js stub 属性

javascript - 如何按尺寸打印 以 a4 尺寸打印出来

javascript - MDL 选项卡加载问题

jquery - 如何在div中动态添加滚动条?

javascript - 左边有圆形的 CSS 三 Angular 形边?第2部分

php - 来自 mysql 表的时间和日期回显

php - MySQL + PHP - 根据先前的选择结果选择信息