2

I'm trying to save an image in Postgresql Database but unable to do that I'm trying to call a function in which I need to Pass image in bytea code.

function to store Image is

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;
Mani Deep
  • 1,298
  • 2
  • 17
  • 33
Zoro
  • 120
  • 9
  • What is the error your are getting? – Mani Deep May 04 '15 at 13:00
  • @ManiDeep I'm trying to save Image but as it defined in the function I'm not able to convert that image in bytea, and it's not returning any error – Zoro May 04 '15 at 13:02
  • possible duplicate of [Storing an image in postgresql](http://stackoverflow.com/questions/29816821/storing-an-image-in-postgresql) – Mani Deep May 04 '15 at 13:04

1 Answers1

2

Answer is very simple for this question. Recently I also worked on this and faced same issue that you are facing, you can use below code.

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

// Function that saved Image on local Location

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

I hope this will work for you as this worked for me

Luffy
  • 1,317
  • 1
  • 19
  • 41