【问题标题】:PostgreSQL load images to DBPostgreSQL 将图像加载到数据库
【发布时间】:2018-12-24 06:06:29
【问题描述】:

我已经知道如何在数据库中存储图像,只需在我的表中输入bytea

我已经可以通过我的项目 .net Core 中的代码将图像保存到 DB,我刚刚通过 url 获取图像并像那里一样保存:

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();
  }
}

效果很好

但我需要从我的电脑保存到表格图像

有没有什么办法可以不用宿主机上的代码或者在其他项目中上传图片到数据库,只用本地图片和Postges DB连接?

【问题讨论】:

  • 你见过stackoverflow.com/questions/22288898/…>吗?
  • @Ravi 你看到这个问题被问到了吗? :)
  • 是的,我刚才看到了。如果我在 7 月看到这个,我会在 2018 年 7 月 16 日回答。抱歉回答晚了。我以前没见过这个。抱歉。

标签: postgresql bytea


【解决方案1】:

如果您可以使用psql,则可以使用\lo_import 导入图像,并使用lo_openloread 函数将内容读取为bytea

假设我要将文件chuck.jpg导入到表blobs中,并且文件不超过1000000字节,可以这样:

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

我使用\lo_unlink 来移除临时大对象。

【讨论】:

  • 我怎么理解,我可以连接到 Postgres 所在的主机。我还必须按图像加载。使用此代码我可以上传图片吗?
  • 映像文件位于运行psql 的客户端计算机上。导入图片的服务器可以在任何地方。
  • 这真的是我所期望的——很好。我在 Win10 上使用 PgAdmin - 我找不到用于 win10 的工具 psql - 你可以分享它的链接吗?
  • 如果你安装了 PostgreSQL,psql 也会被安装。从命令行启动它。
  • 不,我没有。仅安装在主机上。好的 - 我可以只安装没有 PostgreSQL 的 psql 吗?
【解决方案2】:

假设图像有以下方案:

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

无需安装任何二进制文件即可更顺利地完成相同的操作(在我的情况下,直接从 pgAdmin 和 Postgresql 11 工作)

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

感谢this 源(用于导入 XML 的函数)的作者。

也正如其他答案lo_open(loid,131072); 中指出的那样,如果需要,可以调整以适应某个最大尺寸。

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 2017-07-06
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多