Use the built-in function pg_read_binary_file()
. It's available since Postgres 9.1 and does exactly what you want. The manual:
Returns all or part of a file. This function is identical to
pg_read_file
except that it can read arbitrary binary data,
returning the result as bytea
not text
; accordingly, no encoding
checks are performed.
This function is restricted to superusers by default, but other users
can be granted EXECUTE
to run the function.
So to ...
Read a zipped file from server into a bytea
column
UPDATE custom_table
SET content = pg_read_binary_file('/tmp/28528026bc302546d17ce7e82400ab7e.zip')
WHERE id = 123;
Considerably faster than any workaround.
Note this restriction, quoting the manual:
Only files within the database cluster directory and the log_directory
can be accessed. Use a relative path for files in the cluster
directory, and a path matching the log_directory configuration setting
for log files.
You can overcome the path restriction with a symlink from your db directory to any other directory. Be wary of possible security implications, though. See:
Also, consider upgrading to a current version of Postgres Postgres 9.4 has reached EOL on February 13, 2020.