使用CouchDB附件提供文件吗? [英] Serving file with CouchDB attachment?

查看:168
本文介绍了使用CouchDB附件提供文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im using Express. i can't figure out how to send an image file to client in a way that it will be displayed to HTML tag <img src='/preview/?doc=xxxxxx&image=img1.jpg'>. I'm using Cradle getAttachment function to communicate with Couchdb https://github.com/flatiron/cradle

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

我不知道reply到底是什么,以及如何在不使用缓冲区的情况下将该图像传输到客户端

i don't know what reply is exactly and how to transfer that image to client without buffer

推荐答案

要将附件从通讯座传输到客户端而不进行缓冲,您可以将其可读流 pipe 传递到响应的 writableStream .

长版

To transfer an attachment from cradle to a client without buffering, you can pipe its readableStream to the reponse's writableStream.

The long version

摇篮db.getAttachment的一种变体返回readableStream(请参阅摇篮的文档).另一方面,express'res对象用作writableStream.这意味着您应该能够*像这样通过管道将附件通过管道发送

A variant of cradle's db.getAttachment returns a readableStream (see streaming from cradle's docs). express' res object on the other hand serves as a writableStream. This means you should be able* to pipe an attachment to it like this:

// 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)
})


*我不在上班,所以可悲的是我无法验证此代码是否可以运行.如果您有任何问题,请给我写信.


*I'm not at work, so sadly I cannot verify this code will run. Drop me a line if you have problems.

这篇关于使用CouchDB附件提供文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆