2016-09-26 37 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

相关问题