我正在尝试使用node-postgres模块将一个小文件存储到postgres数据库中。我知道我应该使用bytea数据类型来做这件事。我遇到的问题是,当我做一些事情时:
fs.readFile path, (err, data) ->
client.query 'UPDATE file_table SET file = $1 WHERE key = $2', [data, key], (e, result) ->
....db中file列的内容是:\x,并且不存储任何内容。如果我将数据缓冲区更改为十六进制,即data.toString(' hex '),文件将被存储,但当我读回该文件时,所有格式都会丢失。
使用node-postgres模块将文件存储到postgres的正确方式是什么?
发布于 2013-01-19 05:47:34
诀窍是编码为十六进制,并在文件前面加上\x。通过返回缓冲区的parseByteA确实支持读回它:
https://github.com/brianc/node-postgres/blob/master/lib/textParsers.js
下面是我从postgres 9.2.2、node.js 0.8.16和node-postgres (npm package='pg') 0.11.2上的磁盘读取镜像的过程:
fs.readFile(loc_on_disk, 'hex', function(err, imgData) {
console.log('imgData',imgData);
imgData = '\\x' + imgData;
app.pgClient.query('insert into image_table (image) values ($1)',
[imgData],
function(err, writeResult) {
console.log('err',err,'pg writeResult',writeResult);
});
});我做了什么把它写了出来
app.get('/url/to/get/', function(req, res, next) {
app.pgClient.query('select image from image_table limit 1',
function(err, readResult) {
console.log('err',err,'pg readResult',readResult);
fs.writeFile('/tmp/foo.jpg', readResult.rows[0].image);
res.json(200, {success: true});
});
});https://stackoverflow.com/questions/13124711
复制相似问题