I am using JSF2.0, jetty server and Postgres database. I want to store mp3 file in database in byte array formet. I upload the byte array of mp3 file. But when I retrive same byte array from database I get byte array of double size and my because of that my mp3 file is not working as well.
public void updateAnnouncementDetail(AnnouncementDetail announcementDetail) { System.out.println("Upload byte array size:" + announcementDetail.getContent().length); Session sess=get Session(); sess.beginTransaction(); sess.save(announcementDetail); sess.getTransaction().commit(); AnnouncementDetail detail; detail = retrieveAnnouncementDetailById(new AnnouncementDetailPK(announcementDetail.getAnnouncementDetailPK().getAnnouncement(), announcementDetail.getAnnouncementDetailPK().getLanguage())); System.out.println("Retrived byte array size:" + detail.getContent().length); }
Output:
Upload byte array size:384440
Retrived byte array size:768879
I dont know why it is happening. I am storing byte array and on the next line I am retriving it. But I get byte array of double size. Let me know if you need more details.
Advertisement
Answer
When dealing with binary data in Postgres, it is important to use proper data binding.
First, data column must be of type BYTEA
. Is that the case?
To store data, use prepared statements and be sure to call setBinaryStream()
:
File file = new File("myimage.gif"); FileInputStream fis = new FileInputStream(file); PreparedStatement ps = conn.prepareStatement( "INSERT INTO images VALUES (?, ?)" ); ps.setString(1, file.getName()); ps.setBinaryStream(2, fis, (int)file.length()); ps.executeUpdate(); ps.close(); fis.close();
To retrieve data, also use prepared statements and use getBytes()
:
PreparedStatement ps = conn.prepareStatement( "SELECT img FROM images WHERE imgname = ?" ); ps.setString(1, "myimage.gif"); ResultSet rs = ps.executeQuery(); while (rs.next()) { byte[] imgBytes = rs.getBytes(1); // use the data in some way here } rs.close(); ps.close();
See more here.