2015-05-11 343 views
-1

我需要使用ajax上傳圖片。詳細闡述我的觀點: 我需要將我的圖像數據傳遞給PHP頁面,並檢查文件的類型,大小,名稱和所有其他屬性。如果所有的屬性匹配,那麼只有我需要傳輸文件。這裏的問題是數據的傳遞只能以JSON(AJAX)格式完成。更重要的是,我不必將其轉換爲base64。使用ajax上傳圖片(json)

如果你能幫助我,你是最受歡迎的。

在此先感謝。

+0

你到目前爲止嘗試了什麼?無論如何,你可以通過ajax作爲* base64 *字符串發送你的圖像 – kosmos

+0

我不必將它轉換爲base 64 @kmsdev –

+1

如果你打算用JSON傳遞它,你別無選擇,只能用base64。 – Misunderstood

回答

1

SO中的想法是處理OP當前代碼。我的意思是,我們不是在這裏做所有的工作,因爲它應該有一個價格。無論如何,這裏是你的問題的解決方法:

使用JavaScript將圖像轉換爲base64。這個有用的方法就像一個魅力:

// Code taken from MatthewCrumley (http://stackoverflow.com/a/934925/298479) 
function getBase64Image(img) { 
    // Create an empty canvas element 
    var canvas = document.createElement("canvas"); 
    canvas.width = img.width; 
    canvas.height = img.height; 

    // Copy the image contents to the canvas 
    var ctx = canvas.getContext("2d"); 
    ctx.drawImage(img, 0, 0); 

    // Get the data-URL formatted image 
    // Firefox supports PNG and JPEG. You could check img.src to guess the 
    // original format, but be aware the using "image/jpg" will re-encode the image. 
    var dataURL = canvas.toDataURL("image/png"); 

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); 
} 

然後,只需將返回的字符串爲Base64通過Ajax:

$.ajax({ 
    url: 'path/to/your/script.php', 
    type: 'post', 
    data: { paramName: imagedata } // the returned data from above js method, 
    /*...*/ 
}); 

而且,在PHP端,只需將字符串返回到圖像文件:

// Code taken from Austin Brunkhorst (http://stackoverflow.com/a/15153931/3648578) 
function base64_to_jpeg($base64_string, $output_file) { 
    $ifp = fopen($output_file, "wb"); 

    $data = explode(',', $base64_string); 

    fwrite($ifp, base64_decode($data[1])); 
    fclose($ifp); 

    return $output_file; 
} 
+0

謝謝@kmsdev。我會試試這個,讓你知道更新。 –

+0

不客氣,希望你能實現它。注意ajax方法,它需要jQuery – kosmos

+0

你的答案適合我。但是現在一些要求已經改變了。所以我修改了代碼。但仍然有一些問題。你可以看看它 - [http://stackoverflow.com/questions/30166082/how-to-fetch-data-from-ajax-in-php] –