2017-04-05 59 views
0

我有一個圖像上傳表單一個非常簡單的HTML頁面如下:從輸入形式發送圖像到PHP腳本的Ajax

<input type='file' id='image_uploaded' accept='image'/> 
<input type='submit' id="upload_image"/> 

到目前爲止,對我的JavaScript,我有:

$(document).ready(function() { 
    $("#upload_image").click(function() { 
     $.ajax({ 
      url: "upload.php", 
      type: "GET", 
      //data: don't know what to put here 
      success: function(data) { 
       alert(data); 
      } 
     }); 
    }); 
}); 

upload.php到目前爲止只是創建一個目錄來存儲影像,如果該目錄不已經存在:

<?php 
    define("IMAGE_DIRECTORY", "images"); 

    //If the directory for images does not exist, create it 
    if(!is_dir(IMAGE_DIRECTORY)) { 
     mkdir(IMAGE_DIRECTORY, 0777, true); 
    } 
?> 

所以我我不確定如何將圖像發送到Ajax調用中的PHP腳本,然後如何處理PHP中的圖像以將其保存到文件夾?

+0

所以這是兩個問題。我建議你研究如何處理圖像的服務器端。我相信你會在網上找到很多例子。 – NewToJS

回答

0

有建立在PHP變量來幫你如_FILES $所以只是這樣做:
首先,改變你的AJAX類型"POST"而不是"GET"
然後將這些行的代碼存儲圖像:

if(!move_uploaded_file($_FILES["file"]["tmp_name"], "path/to/file/".basename($_FILES["file"]["name"]))){ 
    die("Sorry, there was an error uploading your file."); 
} 
+0

謝謝,但是我怎樣才能讓圖像到達PHP文件呢? – lillemap