【问题标题】:Trying to Store Image from web-service in Postgresql Database尝试将来自 Web 服务的图像存储在 Postgresql 数据库中
【发布时间】:2015-07-13 20:42:21
【问题描述】:

我正在尝试将图像保存在 Postgresql 数据库中,但无法执行此操作,我正在尝试调用一个函数,在该函数中我需要在 bytea 代码中传递图像。

图片存储功能

CREATE OR REPLACE FUNCTION products_update_image(product_id character varying, img bytea)
RETURNS void AS
'BEGIN UPDATE PRODUCTS SET IMAGE=img::bytea WHERE ID=product_id; END;'
    LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION products_update_image(character varying, bytea)
  OWNER TO postgres;

【问题讨论】:

  • 您遇到的错误是什么?
  • @ManiDeep 我正在尝试保存图像,但正如函数中定义的那样,我无法在 bytea 中转换该图像,并且它没有返回任何错误

标签: java postgresql pgadmin openbravo


【解决方案1】:

这个问题的答案很简单。最近我也在解决这个问题,遇到了和你一样的问题,你可以使用下面的代码。

// Save an image from server to physical location
String destinationFile = "C:\\Program Files (x86)\\openbravopos-2.30.2\\image1.jpg";

// This will call a function which will save an image on your given Location
saveImage(image, destinationFile);

// You don't need to call procedure here just pass this query
PreparedStatement pstmt = con.prepareStatement("UPDATE PRODUCTS SET IMAGE = ? WHERE ID = ?");

// Location of image with it's name
File file = new File("Location\\image1.jpg");
FileInputStream in = new FileInputStream(file);
try
{
    pstmt.setBinaryStream(1, in, (int) file.length());
    pstmt.setString(2, id);
    pstmt.executeUpdate();
}
catch (Exception ee)
{
    System.out.println("Exception is:- " + ee);
}

// 将图像保存到本地位置的函数

public static void saveImage(String imageUrl, String destinationFile) throws IOException
{
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream(destinationFile);

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1)
    {
        os.write(b, 0, length);
    }

    is.close();
    os.close();
}

我希望这对你有用,因为这对我有用

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多