使用 cradle getAttachment 从 CouchDB 获取二进制文件?
我上传了一个 png 作为附件到 CouchDb 数据库。当我通过蒲团查看它时,它很好,如果我尝试通过摇篮取回它,它就会损坏。我使用了 crade 附带的 crade-test.js 中的一个片段,并对它进行了一些修改:
var response = {};
var streamer = db.getAttachment(data.id,filename);
streamer.addListener('response', function (res) {
response.headers = res.headers;
response.headers.status = res.statusCode;
response.body = "";
});
streamer.addListener('data', function (chunk) { response.body += chunk; });
streamer.addListener('end', function () {
fs.writeFile('new-'+filename, response.body, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
结果是一个比输入更大的损坏的 png。我在这里提供了一个工作示例: http://jsfiddle.net/x8GZc/
I uploaded a png as attachment to a CouchDb database. When I have look at it via Futon it is fine, if I try to get it back via cradle it is corrupted. I used a snipptlet from the crade-test.js shipped with crade and modified it a bit:
var response = {};
var streamer = db.getAttachment(data.id,filename);
streamer.addListener('response', function (res) {
response.headers = res.headers;
response.headers.status = res.statusCode;
response.body = "";
});
streamer.addListener('data', function (chunk) { response.body += chunk; });
streamer.addListener('end', function () {
fs.writeFile('new-'+filename, response.body, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
The result is a corrupted png that is bigger than the input. I provided a working example here: http://jsfiddle.net/x8GZc/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您找到的代码片段与文本文档(=基本上是一个字符串)一起使用。
对于二进制数据(例如图像),您必须在响应对象上设置正确的编码:
The snippet you found is used with a text document (= basically a string).
For binary data (e.g. images), you must set the correct encoding on the response object: