尝试将来自 Web 服务的图像存储在 Postgresql 数据库中

Trying to Store Image from web-service in Postgresql Database

我正在尝试将图像保存在 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;

这个问题的答案很简单。最近我也在研究这个,遇到了你面临的同样问题,你可以使用下面的代码。

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

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