用CouchDB附件提供文件?

我使用Express。 我不知道如何发送一个图像文件到客户端的方式,它会显示为HTML标记<img src='/preview/?doc=xxxxxx&image=img1.jpg'> 。 我正在使用Cradle getAttachment函数与Couchdb进行通信https://github.com/flatiron/cradle

 db.getAttachment(id, filename, function (err, reply) { set('Content-Type', 'image/png'); res.end(reply); }); 

我不知道reply是什么,以及如何将这个图像无缓冲地转移到客户端

要将附件从摇篮传输到客户端而不缓冲,可以将其可读stream插入到响应的可写stream中

长版

cradle的db.getAttachment一个变体返回一个readableStream (参见摇篮文档的stream媒体 )。 另一方面表示' res对象作为一个writableStream 。 这意味着你应该能够*像这样pipe道附件:

 // respond to a request like '/preview/?doc=xxxxxx&image=img1.jpg' app.get('/preview/', function(req, res){ // fetch query parameters from url (?doc=...&image=...) var id = req.query.doc var filename = req.query.image // create a readableStream from the doc's attachment var readStream = db.getAttachment(id, filename, function (err) { // note: no second argument // this inner function will be executed // once the stream is finished // or has failed if (err) return console.dir(err) else console.dir('the stream has been successfully piped') }) // set the appropriate headers here res.setHeader("Content-Type", "image/jpeg") // pipe the attachment to the client's response readStream.pipe(res) }) 

或者稍微短一些:

 app.get('/preview/', function(req, res){ res.setHeader("Content-Type", "image/png") db.getAttachment(req.query.doc, req.query.image, someErrorHandlerFunction).pipe(res) }) 

*我不在工作,所以可惜我无法validation此代码将运行。 如果你有问题,请给我一条线。