2016-02-16 28 views
1

我已經研究過這樣做的最佳方式,並在各種演示中不斷收到相互衝突的信息和建議。使用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目錄中,稍後將在代碼中進一步處理,以便將其上傳到頭像服務。

在此先感謝。

+0

我使用[ajaxForm](http://malsup.com/jquery/form/#file-upload)上傳文件 – roullie

回答

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

您應該將問題標記爲已回答。 –

+0

根據我點擊打勾的時間,我不能將自己的問題標記爲72小時回答,顯然這是爲了讓其他人有機會張貼自己的答案,以防他們的答案更好。 –

+0

對我很好,但用'$ _FILES'改變了'$ _GET [「files」]''。 – Meloman

相關問題