我正在尝试使用 node-postgres 模块将一个小文件存储到 postgres 数据库中。我知道我应该使用 bytea 数据类型来执行此操作。我遇到的问题是当我做类似的事情时:
fs.readFile path, (err, data) ->
client.query 'UPDATE file_table SET file = $1 WHERE key = $2', [data, key], (e, result) ->
....
数据库中文件列的内容是:\x 并且没有存储任何内容。如果我将数据缓冲区更改为十六进制,即 data.toString('hex') 文件被存储,但当我读回文件时所有格式都丢失了。
使用 node-postgres 模块将文件存储到 postgres 的正确方法是什么?
最佳答案
诀窍是编码为十六进制并在文件前加上\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});
});
});
关于node.js - 使用 node-postgres 在 postgres 中存储文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13124711/