2016-12-06 92 views
0

我目前正在使用Dropbox開發一個web應用程序的功能,我對它有點新。該功能涉及使用HTML 5 Canvas進行圖像編輯並將畫布圖像保存到Dropbox。JavaScript使用API​​ v2將base64圖像數據寫入Dropbox

我想要做的是將畫布圖像轉換爲base64圖像數據,並直接在客戶端使用JavaScript寫Dropbox。

由於Dropbox API v1現在已被棄用,我試圖在v2中實現此功能。

我已經做了一些挖掘,但大多數的例子我能找到使用在版本1的API WriteFile的方法,像這樣的: Save image to dropbox with data from canvas

,所以我只是想知道我可以得到這個一起工作v2 API?

感謝先進。

+0

你有任何代碼,你沒試過嗎?你真的必須將它編碼爲base64編碼的字符串嗎?您應該可以將其作爲常規Blob文件上載。 –

+0

不,我不必將它編碼爲base64字符串。 是的,我可以提供一些代碼,只是我仍然在POC階段,我正在探索不同的方法。 – SunnyHoHoHo

+0

[官方Dropbox API v2 JavaScript SDK](https://github.com/dropbox/dropbox-sdk-js)和[本示例](https://github.com/dropbox/dropbox-sdk-js/blob /master/examples/upload/index.html#L49)可能是一個很好的起點。 – Greg

回答

0

希望這可以幫助未來的人。

你需要像這樣

var canvas = document.getElementById("paint"); 

然後

function uploadFile() { 
    var ACCESS_TOKEN = "xxx"; 
    var dbx = new Dropbox({ 
    accessToken: ACCESS_TOKEN 
    }); 
    var fileInput = document.getElementById('file-upload'); 
    var file = fileInput.files[0]; 


    //Get data from canvas 
    var imageSringData = canvas.toDataURL('image/png'); 
    //Convert it to an arraybuffer 
    var imageData = _base64ToArrayBuffer(imageSringData); 


    dbx.filesUpload({ 
     path: '/' + "test.png", 
     contents: imageData 
    }) 
    .then(function(response) { 
     var results = document.getElementById('results'); 
     results.appendChild(document.createTextNode('File uploaded!')); 
     console.log(response); 
    }) 
    .catch(function(error) { 
     console.error(error); 
    }); 
    return false; 
} 



function _base64ToArrayBuffer(base64) { 
    base64 = base64.split('data:image/png;base64,').join(''); 
    var binary_string = window.atob(base64), 
    len = binary_string.length, 
    bytes = new Uint8Array(len), 
    i; 

    for (i = 0; i < len; i++) { 
    bytes[i] = binary_string.charCodeAt(i); 
    } 
    return bytes.buffer; 
}