使用 Node Multer 缓冲区获取 Blob 并将 Blob 转换为 Base 64

Get the Blob Using Node Multer Buffer And Convert Blob To Base 64

我正在尝试将 Uint8Contents 作为 Blob 转换为 base64 并将其存储为来自 ArrayBuffer/Buffer 的 PgSQL bytea 使用 multer Expressjs 的中间件。

大部分的回答都是先保存到文件系统中,但是你会怎么使用multer memory storage呢? (我就是这样用的)

import { Router, Request, Response } from 'express'
import multer from 'multer'

const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
const api = Router()

api.post('/customer/:customer_id/photo', upload.single('photo'),
    async (req: Request, res: Response) => {

    const customerId = req.params.customer_id
    const photoBuffer = req?.file?.buffer as Buffer

    const arrayBuffer = photoBuffer.buffer.slice(
      photoBuffer.byteOffset,
      photoBuffer.byteOffset + photoBuffer.byteLength
    )

    const uInt8Contents = photoBuffer.readUInt8(photoBuffer.byteOffset)
    console.log("uInt8Contents",uInt8Contents)

    // const arrayBuffer = Uint8Array.from(photoBuffer).buffer
    // const photoBlob = Buffer.from(arrayBuffer).Blob([arrayBuffer])
    console.log("bufferPhoto", arrayBuffer)

    // TODO: Need a code for converting array buffer or buffer to be the correct image Blob

    const base64Photo = Buffer.from(arrayBuffer).toString('base64')
    // Store base 64 photo in PgSQL bytea
    // ...
  }
)

我只是不知道如何将正确的 Blob 转换为 base64 并将其作为 bytea.

存储在 PgSQL 中

所以,问题是:在倒数第二行,我如何将文件转换成 Blob?

我得到了这个输出,但它似乎不是 blob 的 Uint8Contents,因为图像根本不显示。

ArrayBuffer {
  [Uint8Contents]: <ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff e2 02 a0 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 02 90 6c 63 6d 73 04 30 00 00 6d 6e 74 72 52 47 42 20 58 59 5a 20 07 dd 00 0a 00 08 00 17 00 2b 00 36 61 63 73 70 41 50 50 4c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... 2527 more bytes>,
  byteLength: 2627
}

我发现了这个问题: https://github.com/dherault/serverless-offline/issues/464

这基本上是一个 serverless-offline 问题:当服务器在 serverless-offline 中 运行 并且上传图像时,二进制图像会像这样扭曲:

二值图像应该是这样的,而不是:

简而言之,字符正在被 serverless-offline 更改。然而,link 建议如果您要在 non-serverless-offline 环境中部署代码,它会起作用。

因此,此代码在部署时仍然有效:

import { Router, Request, Response } from 'express'
import multer from 'multer'

const storage = multer.memoryStorage()
const uploadPhoto = multer({ storage: storage }).single('upload')
const api = Router()

v1Api.post('/user/:user_id/photo', uploadPhoto, async (req: Request, res: Response) => {
  const userId = req.params.user_id
  const photoBuffer = req?.file?.buffer as Buffer
  const binaryPhoto = Buffer.from(photoBuffer).toString('binary')
  const base64Photo = Buffer.from(binaryPhoto).toString('base64')
  console.log(base64photo) // Save this base64photo as bytea
})

否则,配置 serverless.yml 以使用此插件支持二进制文件 aws-serverless-express-binary

编辑

我们将它部署在一个环境中,它似乎工作正常。