database - Using Java, I upload an image to postgres DB size is 4000. But when I download it, the size is 8000 -
here latest code. wanted try different still getting same results.
i using postgres db , created column called file data type bytea. image uploaded db (i can see in there when view table's data).
i tried several images. size appears correct when upload doubles in size when download it. (which breaks image).
any on why not working appreciated.
public void uploadimage(file image, string imagename) throws sqlexception { try { conn = connectionmanager.connecttodb(); string sql = "insert images (name, file) "+ "values(?,?)"; system.out.println("your image name " + imagename); system.out.println("uploaded image name " + image); preparedstatement stmt = conn.preparestatement(sql); stmt.setstring(1,imagename); fis = new fileinputstream(image); stmt.setbinarystream(2, fis, (int) image.length()); system.out.println("image size = " +image.length()); stmt.execute(); conn.commit(); } catch (sqlexception e) { system.out.println("could not insert db"); e.printstacktrace(); } catch (filenotfoundexception e) { system.out.println("could not insert db"); e.printstacktrace(); } { //close db objects try { fis.close(); } catch (ioexception e) { e.printstacktrace(); } conn.close(); } } public void downloadimagefromdb(string imagename) throws sqlexception { connectionmanager connectionmanager = new connectionmanager(); try { conn = connectionmanager.connecttodb(); statement downloadimagestatement = conn.createstatement(); downloadimagestatement.executequery("select file images name = '"+imagename+"'"); resultset rs = downloadimagestatement.getresultset(); int i=1; inputstream in = null; int returnvalue = 0; if(rs.next()) { string len1 = rs.getstring("file"); int len = len1.length(); byte [] b = new byte[len]; in = rs.getbinarystream("file"); int index = in.read(b, 0, len); outputstream outimej = new fileoutputstream("c:\\eclipseprojects\\strutshelloworld\\"+imagename+".jpg"); while (index != -1) { outimej.write(b, 0, index); index = in.read(b, 0, len); system.out.println("=========================="); system.out.println(index); system.out.println(outimej); system.out.println("=========================="); } outimej.close(); }else { returnvalue = 1; } downloadimagestatement.close(); conn.close(); } catch (sqlexception e) { system.out.println("could not image db"); e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } { // close db objects. conn.close(); } //return imgdata; }
you don't want use inputstream.available()
measure size. here's q&a describes available()
- in short, not that's useful.
one (correct) way actual size check size of file
after you've written it, using file.length()
.
Comments
Post a Comment