2014-02-21 103 views

回答

10

我遇到的常見方式是使用Base64字符串方法:將圖像編碼爲Base64字符串,並將其設置爲您發送到服務器的JSON對象的一部分。

另一種方法似乎是在JSON中使用二進制數據,但我從來沒有嘗試過,所以沒有從我這麼多的信息。

Here's一個代碼示例在Javascript中執行Base64編碼。具體看下面的方法

function getBase64Image(imgElem) { 
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18" 
    var canvas = document.createElement("canvas"); 
    canvas.width = imgElem.clientWidth; 
    canvas.height = imgElem.clientHeight; 
    var ctx = canvas.getContext("2d"); 
    ctx.drawImage(imgElem, 0, 0); 
    var dataURL = canvas.toDataURL("image/png"); 
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); 
} 
+0

我正在使用Python Flask框架,所以我怎麼能從base64字符串中獲取圖像回來python? –

8

有一種方法可以實現這一點:使用圖像數據。

在Javascript中,在客戶端,FileReader將允許您讀取二進制圖像數據,並將它們轉換爲base64編碼的字符串。

在客戶端:編碼圖像

var file = $('.file-upload > input')[0].files[0]; 

function upload(file) { 
    var reader = new FileReader(); 

    // when image data was read 
    reader.onload = function(event) { 
    // I usually remove the prefix to only keep data, but it depends on your server 
    var data = event.target.result.replace("data:"+ file.type +";base64,", ''); 

    // make here your ajax call 
    $.ajax({ 
     url: 'and_so_on', 
     json: { 
     data: data 
     } 
    }); 

    // read data from file 
    reader.readAsDataURL(file); 

}

在服務器端,您將收到的base64可以easilly與緩衝構造

var buffer = new Buffer(data, 'base64'); 

翻譯成二進制被警告該FileReader是not supported by all browsers

+0

我做什麼來支持所有瀏覽器? – Phoenix

+0

您也可以使用[btoa()](https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa)([瀏覽器支持](http://caniuse.com/) #feat = atob-btoa))函數與reader.readAsBinaryString(file)一起創建base64字符串(var data = btoa(event.target.result))。然後你不需要做字符串替換。 –

+0

btoa也只支持IE10 –

相關問題