toString () & # 39; base64 # 39;在节点返回无效的图像数据
toString('base64') In Node Returns Invalid Image Data
我目前有一个网站,我向服务器发送GET
请求,并期望它从网站下载图像并将数据发送回客户端。如果我将下载的结果数据直接写入文件,它就可以工作了。
app.get('/image', function(req, res) {
request("http://ipcam/auto.jpg", {encoding: 'binary'}, function(err, response, body) {
if (err) res.send(err);
fs.writeFile('logo ' + (Math.random() * 1000).toFixed(0) + '.jpeg', body, 'binary', function(err){
if (err) throw err
console.log('File saved.')
})
res.send(200);
});
});
然而,当我尝试使用Buffer
对象将其转换为base64然后将其发送到客户端时,img
标签不将其识别为有效的图像数据。使用显示base64图像数据预览的在线实用程序证实了这一点。
res.send(new Buffer(body.replace(/('r'n|'n|'r)/gm,""), 'binary').toString('base64'));
客户:var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200 && xmlHttp.responseText != undefined) {
var base64string = xmlHttp.responseText.replace(/('r'n|'n|'r)/gm,"");
document.getElementById('image').src = 'data:image/jpeg;base64,' + base64string;
}
};
xmlHttp.open("GET", '/image', true);
xmlHttp.send();
编辑:我删除了删除换行符的正则表达式。
当前服务器:res.send(new Buffer(body, 'binary').toString('base64'));
当前客户端:
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200 && xmlHttp.responseText != undefined) {
document.getElementById('image').src = 'data:image/jpeg;base64,' + xmlHttp.responseText;
}
};
xmlHttp.open("GET", '/image', true);
xmlHttp.send();
{编码:"二进制"}
如果你想让请求将响应解释为二进制数据,你应该指定encoding: null。
(引用)
一旦你这样做,你在响应中得到的体将被设置为Buffer,所以你可以直接执行:encoding -响应数据的setEncoding使用的编码。如果为空,主体作为Buffer返回。其他任何内容(包括默认值)value (undefined)将作为编码参数传递给toString()(这意味着它在默认情况下是有效的utf8)。(注意:如果您希望二进制数据,你应该设置encoding: null)
body.toString('base64')
res.send(new Buffer(body.replace(/('r'n|'n|'r)/gm,""), 'binary').toString('base64'));
没有多大意义,你不是在发送二进制数据,而是在发送字符串。所以尝试。
res.send(new Buffer(body).toString('base64'));
相关文章:
- 下周末'javascript中的s datetime返回无效日期
- angular payments返回带有测试数据的无效卡
- jquery focusin没有'调用.focus()并返回false;时无效;
- Apache poi XSSF创建Excel文件-Create返回格式或文件扩展名无效的空文件
- 为什么MooTools JSON.encode()返回“$呼叫者”:无效的
- jquery ajax中的无效返回
- 返回的日期无效
- 为 Javascript 节点列表返回的长度无效
- 返回无效 0;vs 返回;.
- 返回无效日期格式的本地存储
- JWT 返回无效签名错误,即使我在授权中输入令牌也是如此
- ajaForm 在 responseXML 中返回无效的 XML
- JQuery 不返回值?或者该方法无效
- YouTube feed API (JSON-P) 返回无效的 JS
- 必须返回有效的 ReactComponent.您可能返回了未定义的数组或其他一些无效对象
- 将包含内容和元数据的文件上传到谷歌文档会返回400无效/错误请求
- 返回字符对于SimpleText区域和Validation TextBox的混合无效
- jQuery UI日期选择器getDate今天返回's的日期无效
- Javascript:函数-返回一个对象将使this.variable无效
- Javascript:Uint16Array(length)返回无效参数