Я использую 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
в точности и как передать это изображение клиенту без буфера
Чтобы перенести приложение из подставки на клиентский клиент без буферизации, вы можете передать свой readableStream в файл writeableStream.
Длинная версия
Вариант cradle db.getAttachment
возвращает readableStream
(см. Потоковое видео из док-станции). express ‘ res
object, с другой стороны, служит как writableStream
. Это означает, что вы должны иметь возможность * подключать к нему приложение:
// 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 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 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)
})
* Я не работаю, так что, к сожалению, я не могу подтвердить, что этот код будет работать. Бросьте мне строку, если у вас есть проблемы.