【发布时间】:2021-11-02 13:57:42
【问题描述】:
我正在尝试将 Uint8Contents 作为 Blob 转换为 base64 并将其存储为来自 ArrayBuffer/Buffer 的 PgSQL bytea,使用 Expressjs 的 multer 中间件。
大多数答案都是先将其保存在文件系统中,但是您将如何使用 multer 内存存储? (我是这样用的)
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 并将其存储在 PgSQL 中为 bytea。
所以,问题是:在倒数第二行,如何将文件转换为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
}
【问题讨论】:
-
你是如何访问你的数据库的?使用续集?
-
我不认为它与数据库有任何关系,虽然......因为上传的文件是
multipart/form-data,我们只需要将上传的二进制Blob转换为base64。为了回答您的问题,我们使用了一个名为 Objection 的 ORM。从 pgSQL DB 获取二进制 Blob base64 作为 bytea 已经开始工作了。
标签: node.js base64 blob buffer arraybuffer