2015-04-23 113 views
4

我試圖在Postgresql數據庫中存儲圖像,我有用於在數據庫中存儲圖像的過程,圖像列類型是bytea.I嘗試將我的圖像轉換爲String(Base64)和將其轉換爲字節[],但無法更新該圖像。在postgresql中存儲圖像

代碼來讀取圖像並將其轉換成字符串是這樣的: -

File file = new File("FilePath\\image.jpg"); 

try 
{ 
    // Reading a Image file from file system 
    FileInputStream imageInFile = new FileInputStream(file); 
    byte imageData[] = new byte[(int) file.length()]; 
    imageInFile.read(imageData); 

    // Converting Image byte array into Base64 String By calling encodeImage Function 
    byte[] imageDataString = encodeImage(imageData); 

    CallableStatement statement = con.prepareCall(" { call products_update_image('" + id + "', '" + imageDataString + "') } "); 
    statement.execute(); 
} 
catch (Exception ex) 
{ 
    System.out.println("Exception is:- " + ex); 
} 

public static byte[] encodeImage(byte[] imageByteArray) 
{ 
    return Base64.encodeBase64(imageByteArray); 
} 

我用這個鏈接的圖像Link 下面給出的是它是用來保存圖像數據庫程序轉換。

CREATE OR REPLACE FUNCTION UpdateProfileImage(product_id character varying, img bytea) 

誰能告訴我爲什麼我不能夠存儲這個形象,或者是什麼,我做錯了..

+1

爲什麼不把圖像讀入'ByteArrayOutputStream',它可以讓你訪問'byte []'數據...? – MadProgrammer

+0

@MalProgrammer我也試過這個,但什麼都沒有發生:( – Luffy

+0

也許你應該告訴你嘗試以及你的存儲過程 – MadProgrammer

回答

4

感謝a_horse_with_no_name。我能找到我的問題的解決方案。我不需要調用過程來存儲圖像,我需要將圖像作爲二進制流傳遞。

PreparedStatement pstmt = con.prepareStatement("UPDATE PRODUCTS SET IMAGE = ? WHERE ID = ?"); 
File file = new File("C:\\Program Files (x86)\\openbravopos-2.30.2\\image.jpg"); 
FileInputStream in = new FileInputStream(file); 
try 
{ 
    pstmt.setBinaryStream(1, in, (int) file.length()); 
    pstmt.setString(2, id); 
    pstmt.executeUpdate(); 
    //con.commit 
} 
catch (Exception ee) 
{ 
    System.out.println("Exception is:- " + ee); 
}