问题
I've already know how to store images in DB, just use bytea
type in my table
And I've already can save images to DB via code in my project .net Core, I've just getting image by url
and saving like there:
using (HttpResponseMessage res = await client.GetAsync(photo_url))
using (HttpContent content = res.Content) {
byte[] imageByte = await content.ReadAsByteArrayAsync();
using (NpgsqlConnection conn = new NpgsqlConnection("ConnectionString")) {
conn.Open();
using (NpgsqlTransaction tran = conn.BeginTransaction())
using (NpgsqlCommand cmd = new NpgsqlCommand("Photo_Save", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("photo", NpgsqlTypes.NpgsqlDbType.Bytea, imageByte);
cmd.ExecuteScalar();
tran.Commit();
}
}
It's work well
But I need save to table images from my pc
Is there any way to upload images into the database without the code on the host or in any other project, just use local picture and connection to Postges DB?
回答1:
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.
回答2:
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 .
回答3:
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.
来源:https://stackoverflow.com/questions/51366114/postgresql-load-images-to-db