如何将Postgres bytea列下载为文件

问题描述 投票:28回答:6

[目前,我在bygres中以posttea的形式存储了许多文件。文件类型为.doc,.odt,.pdf,.txt等。

[我可以知道如何下载存储在Postgres中的所有文件,因为我需要进行备份。我需要它们的原始文件类型而不是字节格式。

谢谢!

file postgresql byte
6个回答
40
投票

一个简单的选择是将COPY命令与COPY一起使用以十六进制格式,然后应用encode shell命令(使用-p 连续十六进制转储样式开关)。例如,假设我在示例表的bytea列中有jpg图像:

encode

我检查了它在实践中是否可以使用。


6
投票

尝试一下:

xxd

2
投票

如果要下载的数据很多,那么可以先获取这些行,然后遍历每个行,将bytea字段写入文件。

xxd

0
投票

据我所知,从文件到文件的BYTE需要在应用程序级别完成。

((9.1可能会随着文件系统数据包装程序的贡献而改变。还有一个lo_export函数,但不适用于此处。)


0
投票
\copy (SELECT encode(file, 'hex') FROM samples LIMIT 1) TO
    '/home/grzegorz/Desktop/image.hex'

$ xxd -p -r image.hex > image.jpg

0
投票

这是我想出的最简单的方法:

 COPY (SELECT yourbyteacolumn FROM yourtable WHERE <add your clauses here> ...) TO 'youroutputfile' (FORMAT binary)

$resource = pg_connect('host=localhost port=5432 dbname=website user=super password=************'); // grab all the user IDs $userResponse = pg_query('select distinct(r.id) from resource r join connection c on r.id = c.resource_id_from join resource rfile on c.resource_id_to = rfile.id and rfile.resource_type_id = 10 join file f on rfile.id = f.resource_id join file_type ft on f.file_type_id = ft.id where r.resource_type_id = 38'); // need to work through one by one to handle data while($user = pg_fetch_array($userResponse)){ $user_id = $user['id']; $query = 'select r.id, f.data, rfile.resource_type_id, ft.extension from resource r join connection c on r.id = c.resource_id_from join resource rfile on c.resource_id_to = rfile.id and rfile.resource_type_id = 10 join file f on rfile.id = f.resource_id join file_type ft on f.file_type_id = ft.id where r.resource_type_id = 38 and r.id = ' . $user_id; $fileResponse = pg_query($query); $fileData = pg_fetch_array($fileResponse); $data = pg_unescape_bytea($fileData['data']); $extension = $fileData['extension']; $fileId = $fileData['id']; $filename = $fileId . '.' . $extension; $fileHandle = fopen($filename, 'w'); fwrite($fileHandle, $data); fclose($fileHandle); } 很重要,因为它去除了输出的所有格式。这些选项也可在DO $$ DECLARE l_lob_id OID; r record; BEGIN for r in select data, filename from bytea_table LOOP l_lob_id:=lo_from_bytea(0,r.data); PERFORM lo_export(l_lob_id,'/home/...'||r.filename); PERFORM lo_unlink(l_lob_id); END LOOP; END; $$ shell中使用。

© www.soinside.com 2019 - 2024. All rights reserved.