I'm new to jsp So I want to learn How to save Image In DB and How to retrieve from DB
-
1[1] save - try this http://commons.apache.org/proper/commons-fileupload/using.html [2] retrieve - http://stackoverflow.com/questions/15829367/how-to-display-an-image-from-mysql-database-on-a-jsp-page – Leo Jul 24 '14 at 03:19
-
Try to visit the link http://codejava.net/coding/upload-files-to-database-servlet-jsp-mysql – newuser Jul 24 '14 at 03:19
2 Answers
You can store your images in your database, but it's not advisable and bad practice.
Hello Programmer at first, you'll need to think what's the size(width and height) that you'll use, it's for a little profile photo? it's for a big album photo? I can advise you that if you want to store small images in database, that's ok, to me, but big images must be saved in disk accessed by an url.
When I need to do it, I use a base64 image converted and stored in the datababase like a String, vou VarChar, it depends of your database, but with it you'll need to convert to base64 on upload, and re-convert to image back on show, it's not a problem to current computers.
With this function, we can convert a BufferedImage(most possible to be got by a upload service) to a String, after this we can store it on a DB.
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
and with this method we can convert a String back to a BufferedImage, and show, or serve, on a jps file.
public static BufferedImage decodeToImage(String imageString) {
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
obviusly my answer don't envolves all aspects to store on databases, or how jps works with java, but it's only my advice.
Thanks to read it.

- 111
- 3
generally speaking ,as melkysalem said, we store the image's url in DB. when we want to use the image,we just get the url. only.

- 11
- 1
-
This single line could be a nice comment but never serves as an answer. – Shailesh Saxena Jul 24 '14 at 05:03