如何从缓冲区返回文件流?

7

我已经将图像、其字节数和类型存储在 MySQL 数据库中。

当我获取它时,会返回一个图像缓冲区,现在我正在尝试找出如何将其发送回客户端以呈现图像?

路由中的代码:

  const img = await db.images.findByPk(parser.setValueAsBIN(p.id));

   const myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({
    frequency: 10, // in milliseconds.
    chunkSize: img.Length, // in bytes.
  });



 myReadableStreamBuffer.put(img.dataValues.imageData);

下一步是什么?

如果我要记录myReadableStreamBuffer,我只需要:

得到:

Readable {   _readableState:    ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     paused: true,
     emitClose: true,
     autoDestroy: false,
     destroyed: false,
     defaultEncoding: 'utf8',
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },   readable: true,   domain: null,   _events: [Object: null prototype] {},   _eventsCount: 0,   _maxListeners: undefined,   stopped: false,   stop: [Function],   size: [Function],   maxSize: [Function],   put: [Function],   _read: [Function] }

尝试使用buffer.toString(encodingType)将缓冲数据转换为base 64字符串。这应该在客户端中被利用。 - Harish Dhami
1个回答

13

Fastify在reply.send()方法中也支持流和缓冲区。

以下是如何管理它们的方法:


const fs = require('fs')
const { Readable } = require('stream')
const fastify = require('fastify')({ logger: true })

fastify.get('/', (req, reply) => {
  const buffer = fs.readFileSync('demo.png')
  reply.type('image/png') // if you don't set the content, the image would be downloaded by browser instead of viewed
  reply.send(buffer)
})

fastify.get('/stream', (req, reply) => {
  const buffer = fs.readFileSync('demo.png') // sync just for DEMO
  const myStream = new Readable({
    read () {
      this.push(buffer)
      this.push(null)
    }
  })

  reply.type('image/png')
  reply.send(myStream)
})

fastify.listen(3000)

我建议避免使用stream-buffers包,因为它似乎已经不再维护——存在未解决的问题——而且node.js中默认的stream模块已经得到了极大的改进。


如果可以再麻烦您一下。您上面的答案是有效的,但我想知道如何在客户端显示流式图像?我将图像SR属性设置为"http://localhost:4000/cool/uploadHandler/id=11ea9bc5-559b-1d33-a070-00ff98e8d5ab",并将响应类型设置为reply.type('application/octet-stream')。但没有显示任何图像。 - ThunD3eR
1
客户端正在进行ajax请求吗?如果是的话,您可以将<img src="http://localhost:4000/cool/uploadHandler/id=11ea9bc5-559b-1d33-a070-00ff98e8d5ab" />添加到DOM中。 - Manuel Spigolon
当一些最好的答案没有得到赞时,我总是感到惊讶。我喜欢你提供了完整的解决方案和两个完美的例子。 - Darren S
谢谢。我想从SQL数据库中读取数据,将其转换成CSV格式并流式传输。这可能吗?谢谢。 - Alexander Suraphel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接