2013-02-19 61 views
0

我有一個配置文件頁面,默認圖像將是(no_image.jpg)。在此之下,用戶可以上傳他的圖像​​。一旦用戶選擇了圖像並在對話框中單擊打開,圖像應該上傳到服務器,響應應該用他的新圖像替換(no_image.php)。我試着用google搜索和堆疊我需要的確切輸出。但我找不到。上傳圖片並從php獲取響應並重新加載相同的圖像。 AJAX上傳

style

#upload_progress {display:none;} 

HTML

<div id="upload_progress"> 
    </div> 
<form enctype="multipart/form-data" method="post" action=""> 
     <input type="file" name="file" id="file" onchange="uploadFile()"/> 
     <input type="submit" name="submit" /> 
    <form> 

js

var handleUpload = function(event){ 
    event.preventDefault(); 
    event.stopPropagation(); 

    var fileInput = document.getElementById('file'); 

    var data = new FormData(); 

    data.append('ajax', true) 
     data.append('file', fileInput.files); 


    var request = new XMLHttpRequest(); 

    request.upload.addEventListener('progress', function(event){ 
     if(event.lengthComputable){ 
      var percent = event.loaded /event.total; 
      var progress = document.getElementById('upload_progress'); 

      while(progress.hasChildNodes()){ 
       progress.removeChild(progress.firstChild); 
      } 
      progress.appendChild(document.createTextNode(Math.round(percent*100) + '%')) 
     } 
    }); 

    request.upload.addEventListener('load', function(event){ 
     document.getElementById('upload_progress').style.display = 'none'; 
    }); 

    request.upload.addEventListener('error', function(event){ 
     alert('upload failed'); 
    }); 

    request.addEventListener('readystatechagne', function(event){ 
     if(this.readyState == 4){ 
      if(this.status == 200){ 
       var links = document.getElementById('uploaded'); 

       console.log(this.response); 
       var uploaded = eval(this.response); 

       var div, a; 

       div = document.createElement('div'); 
       a = document.createelement(a); 

       a.setAttribute('href', 'files/'+uploaded); 
       a.appendChild(document.createTextNode(uploaded[i])); 

       div.appendChild(a); 
       links.appendChild(div); 

      }else{ 

      } 
     } 
    }); 

    request.open('POST', '/profile'); 
    request.setRequestHeader('Cache-Control', 'no-cache'); 

    document.getElementById('upload_progress').style.display = 'block'; 
    request.send(data); 
} 

window.addEventListener('load', function(event){ 
    var submit = document.getElementById('submit'); 
    submit.addEventListener('click', handleUpload); 
}); 

PHP

if($_FILES['file'] != '') 
{ 
    //print_r($_FILES); 

     $filename = basename($_FILES['file']['name']); 

     $sqlUpdate = mysql_query("UPDATE tableA SET user_img = '".$filename."' WHERE email = '".$userEmail."'"); 
     $newname = '\images\profile/'.$filename; 

     if($_FILES['file']['error'] == 0 && move_uploaded_file($_FILES['file']['tmp_name'], $newname)); 
     $Uploaded = $filename; 
} 

if(!empty($_POST['ajax'])){ 
    die(json_encode($Uploaded)); 
    exit(); 
} 

幫助者將不勝感激。感謝提前!! ...

回答

2

據我所知(可能是我的知識已經過時)您無法通過AJAX發送圖像。

您的形式更改爲

<iframe id="hiddenIframe"></ifram> 
<form enctype="multipart/form-data" method="post" action="pageGettingData.php" target="hiddenIframe"> 
    <input type="file" name="file" id="file" onchange="uploadFile()"/> 
    <input type="submit" name="submit" /> 
<form> 

uploadFile()函數中使用,這將提交表單的代碼。

現在的數據將被上傳作爲一個正常的形式,而是一個隱藏的iframe,不會在你的PHP代碼引起任何重定向等

現在

if($_FILES['file'] != '') 
{ 
    //print_r($_FILES); 

     $filename = basename($_FILES['file']['name']); 

     $sqlUpdate = mysql_query("UPDATE mp_project_buyer_query SET user_img = '".$filename."' WHERE email = '".$userEmail."'"); 
     $newname = '\images\profile/'.$filename; 

     if($_FILES['file']['error'] == 0 && move_uploaded_file($_FILES['file']['tmp_name'], $newname)); 
     $Uploaded = $filename; 

     echo '<script>parent.updateImage("' . $Uploaded . '");'; // add a javascript 
} 

if(!empty($_POST['ajax'])){ 
    die(json_encode($Uploaded)); 
    exit(); 
} 

當PHP將獲得的圖像也將調用一個JS函數,因爲JS在隱藏的Iframe中,我們要調用父文件上的函數。

在HTML文件中

,創建一個新的JS功能updateImage

function updateImage(imgPath){ 
    $('#userImage").attr('src': imgPath); 
} 

這個JS將更新與新上傳的圖片路徑的圖片路徑。您可能需要修復變量和圖像路徑才能使其工作。我只是快速寫下它們

+1

使用'XHR2'您可以通過Ajax處理文件。所以這個'iframe'-解決方案不再需要了;-) http://www.html5rocks.com/en/tutorials/file/xhr2/ – wildhaber 2013-02-19 12:25:53

+0

我在我的文件中犯了一個小錯誤。所以我從早上起就和它一起戰鬥,最後我來到了堆棧。現在我發現了它,並通過ajax。你的答案會很好。謝謝你的努力。!!! – 2013-02-19 12:28:25