我已經研究過這樣做的最佳方式,並在各種演示中不斷收到相互衝突的信息和建議。使用AJAX將頭像上傳到服務器
我的代碼如下...
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目錄中,稍後將在代碼中進一步處理,以便將其上傳到頭像服務。
在此先感謝。
我使用[ajaxForm](http://malsup.com/jquery/form/#file-upload)上傳文件 – roullie