2012-04-25 44 views
11

我有一個畫布,我可以畫到DOM不會有問題,以及爲用戶節省本地使用:上傳HTML5畫布作爲一個blob

storCanvas.toBlob(function(blob) { saveAs(blob, name + ".png");}); 

(注:我已經包括canvas- toBlob.js跨平臺支持,從http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

現在,我想要做的是發送相同的畫布元素到服務器。我以爲我可以做這樣的事情:

storCanvas.toBlob(function(blob) {upload(blob);}); 

where upload(blob);是:

function upload(blobOrFile) 
{ 
    var xhr = new XMLHttpRequest(); 
    xhr.open('POST', 'upload_file.php', true); 
    xhr.onload = function(e) { /*uploaded*/ }; 

    // Listen to the upload progress. 
    var progressBar = document.querySelector('progress'); 
    xhr.upload.onprogress = function(e) { 
     if (e.lengthComputable) 
     { 
      progressBar.value = (e.loaded/e.total) * 100; 
      progressBar.textContent = progressBar.value; 
     } 
    }; 
    xhr.send(blobOrFile); 

} 

(從那兒剽竊:http://www.html5rocks.com/en/tutorials/file/xhr2/

現在,我想我這會工作,但我的PHP頁面(這我可以成功地使用標準的HTML表單做一個POST)報告回(通過螢火蟲)它得到0kB的無效文件。我認爲這個問題是在我轉換成一個blob,但我不知道正確的方式去...

回答

-2

不知道是否要這樣。但是如何將canvas元素轉換爲圖像數據url,然後將其發送到服務器,然後將其寫入服務器。 類似於

function canvas2DataUrl(canvasElementId){ 
    var canvasElement = document.getElementById("canvasElementId"); 
    var imgData = canvasElement.toDataURL("image/png"); 
    return imgData; 
} 
+0

不走這條路。我開始沿着這條路線走,結果比最初想象的要複雜。在將base64解碼爲bin後,仍然缺少頭文件。不妨去文件或blob上傳路線 – gesell 2014-06-14 13:55:25

+0

@gasell同意! – Dewsworld 2015-05-25 02:16:26

4

當我自己瞭解blob時遇到同樣的問題。我認爲這個問題是在提交blob本身通過XMLHttpRequest而不是把它FormData像這裏面:

canvas.toBlob(function(blob) { 
    var formData = new FormData(); //this will submit as a "multipart/form-data" request 
    formData.append("image_name", blob); //"image_name" is what the server will call the blob 
    upload(formData); //upload the "formData", not the "blob" 
}); 

希望這有助於。

-2

您可以使用此模塊上傳blob。

blobtools.js(https://github.com/extremeFE/blobtools.js

//include blobtools.js 
blobtools.uploadBlob({ // upload blob 
    blob: blob, 
    url: uploadUrl, // upload url 
    fileName : 'paste_image.png' // upload file name 
    callback: callback // callback after upload 
});