2016-09-26 15 views
3

當我做一個POST請求的路線,我有又將圖像的二進制數據到img標籤

/generate/image 

我得到這樣的:var文件=

����JFIF��C��C��� ��  
�����+�}Yϭ�F39M>���������>���;��ˋ��uXʽ�w�ڤx\-[2g��k�S���H���m 
[�V?[_W����#��v��}6�[��F�F�%����n�... 
在客戶端

我做的:

var blob = new Blob([file], {type: 'image/png'}); 
var reader = new FileReader(); 

reader.onload = function (e) { 
    $('#result').attr('src', e.target.result); 
}; 

reader.readAsDataURL(blob); 

,但我得到一個腐敗的圖像

我該怎麼辦?

編輯: 如果我做

img.src = 'data:image/png;base64,' + btoa(file); 

我得到:

Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. 
+2

Base64編碼它,並使用[數據URI方案](https://en.wikipedia.org/wiki/Data_URI_scheme) – naomik

+1

'getElementById'不'getElementByID'。 'attr'是一個jQuery函數,而不是JavaScript函數。 – Xufox

+0

Xufox對不起,我有jQuery包括,我確實改變了getElementById,這是一個錯字 – AbdulHamid

回答

2

在你的後臺,你可以做以下操作:

var fs = require('fs'); 
fs.readFile(path to image from you file, 'base64', function(err, buf){ 
     /* Here you can send your base64 image data to client. Your base64 data is in buf. 
     I am using socket. You can just send. Read more about readFile function*/ 
     socket.emit('image upload', { image: true, buffer: buf }); 
}); 

由於我的客戶從套接字接收數據,我稱之爲功能:

socket.on('image upload', function(data){ 
       displayImage(data); 
      }); 

var displayImage = function(data){ 
       var URL = 'data:image/jpg;base64,'+data.buffer; 
       document.querySelector('#img-id').src = URL; 
      }; 

圖像將顯示在img標籤中。 希望這對你有用。

+0

這確實工作!謝謝! – AbdulHamid

1

請不要使用base64和消耗帶寬+ CPU 發送圖像二進制文件,並使用Ajax正確處理它們。 你不應該得到結果作爲一個字符串。將xhr responseType設置爲blob或使用fetch的blob方法。

fetch("/generate/image").then(res => res.blob()) 

當你有blob時,請不要使用文件閱讀器將它變成url。

使用URL.createObjectURL(BLOB)

+0

而且不要使用jquery的Ajax for binary ... – Endless

+0

這也行得通!!!謝謝! – AbdulHamid

相關問題