我的设置:
RDBMS:postgreSQL
数据库名称:四个。
表:用户。
列:头像。
列数据类型:BLOB。
ORM:续集
其他事物包括表达,思考...不是那么重要。
...
问题:
将文件发送到数据库:
app.patch('/user/:id/avatar', upload.single('avatar'), async (req, res) => {
const id = req.params.id
// encode file on base64
const avatarBuffer = Buffer.from(req.file.buffer, 'base64')
// encode back to string to base64.
// the output is pretty much a base64 img. that if i put on any <img> tag src attribte works
const avatarbase64 = avatarBuffer.toString('base64')
// update the avatar column for the user whose have the id fetched in the request params. (i used 3)
await User.update({ avatar: avatarbase64 }, { where: { id } })
// i know there is no response on this route. this is pretty much to test the updload only.
})
从数据库中获取并作为响应发送给客户端。
app.get('/user/:id/avatar', async (req, res) => {
try {
// fetching id from request params and fetching user whose has the image from database.
// (i choose user 3 - the same user that i updated the image.)
const id = req.params.id
const user = await User.findOne({ where: { id } })
if (!user) {
throw new Error('unable to find user.')
}
// on both cases I wrote a simple txt text with the base64 encoded image.
// to check if its ok and it is. on both cases: upload and read, same code, work on any <img> tag.
fs.writeFile('avatar.txt', user.avatar, () => {
console.log('file written.')
})
// set the head content type to accept jpg image (which is the type of the img i am uploading properly.)
res.set('Content-type', 'image/jpg')
// sending to the client.
res.send(user.avatar)
} catch (e) {
res.status(404).send(e)
}
})
好吧,我正在使用potman模拟这些请求,并且当我发送GET请求时,在POSTMAN上的输出是这样的:
帮助* - *