Cli*_*ive 8 postgresql node.js node-postgres
我正在尝试使用node-postgres模块将一个小文件存储到postgres数据库中.我知道我应该使用bytea数据类型来执行此操作.我遇到的问题是当我做一些事情时:
fs.readFile path, (err, data) ->
client.query 'UPDATE file_table SET file = $1 WHERE key = $2', [data, key], (e, result) ->
....
Run Code Online (Sandbox Code Playgroud)
db中文件列的内容为:\ x,不存储任何内容.如果我将数据缓冲区更改为十六进制,即data.toString('hex'),则会存储该文件,但是当我读回文件时,所有格式都会丢失.
使用node-postgres模块将文件存储到postgres的正确方法是什么?
小智 14
诀窍是编码为十六进制并使用\ 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);
});
});
Run Code Online (Sandbox Code Playgroud)
我做了什么把它写回来
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});
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10985 次 |
最近记录: |