【问题标题】:How do I return a file-stream from buffer?如何从缓冲区返回文件流?
【发布时间】:2020-05-22 01:51:15
【问题描述】:

我已经存储了我的图像,它的大小(以字节为单位)和它的类型在一个 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) 将 Buffer 数据转换为 base 64 字符串。这应该在客户端使用。

标签: javascript node.js stream fastify


【解决方案1】:

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 属性设置为“localhost:4000/cool/uploadHandler/…”,并将响应类型设置为 reply.type('application/octet-stream');但没有显示图像。
  • 客户端在做一个ajax请求?如果是这样,您可以将 <img src="http://localhost:4000/cool/uploadHandler/id=11ea9bc5-559b-1d33-a070-00ff98e8d5ab" /> 添加到 DOM
  • 当一些最佳答案没有得到支持时,我总是很惊讶。我喜欢你有完整的交易和两个完美的例子。
猜你喜欢
  • 1970-01-01
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多