2

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

1 回答 1

2

这个问题的答案很简单。最近我也在解决这个问题并遇到了与您相同的问题,您可以使用下面的代码。

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

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

于 2015-05-04T12:53:08.157 回答