关键是将其编码为十六进制并在文件前添加\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包='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});
});
});
psql
检查插入数据库的数据,看看是否正确。这将告诉你问题是在于正确地插入数据还是读取数据。你还需要提及你的 Pg 版本; 默认的bytea
格式从 9.0 开始从escape
改为hex
。 - Craig Ringernode-postgres
版本是什么?看起来它在一年前就支持了bytea(https://github.com/brianc/node-postgres/pull/38),所以你应该能够直接传递一个缓冲区。 - Craig Ringer