2012-10-14 46 views
14

我在Heroku(雪松env)上有一個rails應用程序。它有一個頁面,我使用toDataURL()方法將畫布數據渲染成圖像。我試圖使用JavaScript(繞過服務器端)將返回的base64圖像數據字符串直接上傳到s3。問題是由於這不是一個文件,我如何直接將base64編碼數據上傳到S3並將其保存爲文件?如何僅使用JavaScript將base64編碼圖像數據上傳到S3?

回答

23

我已經找到一種方法來做到這一點。經過大量的搜索查看不同的教程。

如果您正在處理多個文件,您必須將數據URI轉換爲blob,然後使用CORS將該文件上載到S3我對每個文件都有單獨的XHR請求。

我發現這個功能,將你的數據URI到一個能夠直接使用CORS(Convert Data URI to Blob

function dataURItoBlob(dataURI) { 
    var binary = atob(dataURI.split(',')[1]); 
    var array = []; 
    for(var i = 0; i < binary.length; i++) { 
     array.push(binary.charCodeAt(i)); 
    } 
    return new Blob([new Uint8Array(array)], {type: 'image/jpeg'}); 
} 

Here is a great tutorial on uploading directly to S3, you will need to customise the code to allow for the blob instead of files.

3

被上傳到S3斑點如果有人關心:這裏是coffescript上面給出的函數版本!

convertToBlob = (base64) -> 
    binary = atob base64.split(',')[1] 
    array = [] 
    for i in [0...binary.length] 
     array.push binary.charCodeAt i 
    new Blob [new Uint8Array array], {type: 'image/jpeg'} 
4

Jamcoope的回答非常好,但blob構造函數不被所有瀏覽器支持。最顯着的是android 4.1和android 4.3。有Blob polyfill,但xhr.send(...)不適用於polyfill。最好的選擇是這樣的:

var u = dataURI.split(',')[1], 
    binary = atob(u), 
    array = []; 

for (var i = 0; i < binary.length; i++) { 
    array.push(binary.charCodeAt(i)); 
} 

var typedArray = Uint8Array(array); 

// now typedArray.buffer can be passed to xhr.send 
相關問題