2017-01-17 30 views
-1

我想讀取生成的圖像併發送到服務器。發佈由createObjectURL創建的圖像

<img id="image" src="blob:null/31070c0f-23c0-44b0-945f-57ed1e623350"> 

此代碼生成圖像。

var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function(){ 
    if (this.readyState == 4 && this.status == 200){ 

     var img = document.getElementById('image'); 
     var url = window.URL || window.webkitURL; 
     img.src = url.createObjectURL(this.response); // this one created the image. 

我想讀取要發佈的數據。我試圖將它附加到文件(不工作),試圖從圖像讀取二進制文件(不工作 - 圖像是本地blob),我試圖設置圖像的src文件(不工作)

} 
} 
xhr.open('GET', 'http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl=http://www.cognation.net/profile'); 
xhr.responseType = 'blob'; 
xhr.send(); 

<img id="image" /> 

這是如何呈現圖像。我想將它發送到服務器。 This is how the image is rendered

我試過一些方法,無法回答。

回答

0
var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function(){ 
    if (this.readyState == 4 && this.status == 200){    

     var reader = new FileReader(); 

     reader.onload = function (e) { 
      var dataURL = reader.result; 
      $("#image").attr("src", dataURL); 

      alert($("#ImageTwo").attr("src")); 
     } 

     var read = reader.readAsDataURL(this.response); 

    } 
} 
xhr.open('GET', 'http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl=http://www.cognation.net/profile'); 
xhr.responseType = 'blob'; 
xhr.send(); 
1

要通過發送POST圖像直接發送BLOB感謝FormData API
要轉換一個blob到dataURI,使用FileReader
但你的情況FORMDATA方法應優先。

只是關於使用畫布的說明:這將解碼圖像,然後用不同的算法重新編碼。輸出將不會是相同的圖像。

+0

現在我有這個問題。試圖糾正它,dataurl產生空白圖像。 –

+0

無法從畫布產生圖像,它是空白的。你能告訴我文件閱讀器從img標籤發送圖像嗎? –

+0

@ARUNEdathadan,以xhr接收到的blob(可能仍然在'xhr.response'中,但更安全的是將其保存在與上載函數相同範圍內的變量中)。然後,因爲你想要的是上傳這個圖像,使用'var form = new FormData(); form.append('file',blob,'filename.ext')'然後創建一個POST xhr並調用'postXHR.send(form)'。如果您需要將其作爲dataURI存儲,請執行轉換服務器端。 – Kaiido