简体   繁体   中英

Image save and retrieve as byte array in postgres using java

Please help me and give me a example to save images as byte array and retrieve them. I am using Java and postgre sql is the database I am use.\\

    if (this.files && this.files[0]) {
        var FR= new FileReader();
        FR.onload = function(e) {
          imageArray[index] =  e.target.result;
          FR.readAsDataURL( this.files[0] );
      }
    });

this use to get the image..

imageByte1 = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

then retrive through,

new sun.misc.BASE64Encoder().encode(item.getImage1())

this is use to convert. But out put is different from the what I save.

You're storing binary as base64 in the DB, by the looks. Using a pair of mismatched input and output routines, one of which is not even public API ( com.sun. space).

Please don't.

Use JDBC's support for blobs with java.sql.Types.BLOB , via java.sql.PreparedStatement and bind parameters. Please. The corresponding PostgreSQL data type for the column should be bytea .

In PostGres the data type for byte array (byte []) is bytea . So use the data type for create the column.

Saving:

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

Retrive:

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); OR  byte []out = (byte[])(rs.getObject(1));
    // use the data in some way here
}
rs.close();
ps.close();

Help: Storing Binary Data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM