PostgreSQL load images to DB

丶灬走出姿态 提交于 2019-12-06 09:27:24

If you can use psql, you could use \lo_import to import the image and the lo_open and loread functions to read the contents as a bytea.

Assuming that I want to import file chuck.jpg into a table blobs, and the file does not exceed 1000000 bytes, that could be done like this:

test=> \lo_import chuck.jpg 
lo_import 152237

test=> INSERT INTO blobs VALUES (1, loread(lo_open(152237, 131072), 1000000));
INSERT 0 1

test=> \lo_unlink 152237
lo_unlink 152237

I used \lo_unlink to remove the temporary large object.

Click here!

Here we have given three kinds of solutions try this one once.And let me know if you still have any issues. We can save the image as blob ,bytea .

Assuming following scheme for images:

CREATE TABLE images (
  owner_id uuid references users(user_id), 
  image_id uuid primary key,
  added_timestamp timestamp with time zone,
  img bytea
);

This one can do same thing more smoothly without any binaries to be installed (works directly from pgAdmin with Postgresql 11 in my case)

create or replace function img_import(filename text)
  returns void
  volatile
  as $$
    declare
        content_ bytea;
        loid oid;
        lfd integer;
        lsize integer;
    begin
        loid := lo_import(filename);
        lfd := lo_open(loid,131072);
        lsize := lo_lseek(lfd,0,2);
        perform lo_lseek(lfd,0,0);
        content_ := loread(lfd,lsize);
        perform lo_close(lfd);
        perform lo_unlink(loid);

    insert into images values
    (uuid('66032153-0afc-4124-a50a-c4ea386f4684'), 
    uuid_generate_v4(),
    now(),
    content_);
    end;
$$ language plpgsql

Credits to author of this source (function for importing XML).

Also as pointed out in other answer lo_open(loid,131072); can be adjusted to fit some maximum size if needed.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!