I have read numerous questions on StackOverFlow and other tutorials, that it is always better to store images in a file and then store their unique reference in a database. I am trying to do so but I ended up doing the following. I have created a Maven project and created a folder images under src/main/resources folder in which I have three images. Below is my code:
public class ImageHelper
{
private static final String IMAGE_FILE = "/images/1984.jpg";
Connection conn =null;
Statement statement = null;
PreparedStatement preparedStatement = null;
int byteArrayLength =0;
ConnectionClass newConnection = new ConnectionClass();
InputStream imageStream = null;
int imageFileLength;
//Link reference http://stackoverflow.com/questions/13967307/reading-from-src-main-resources-gives-nullpointerexception
//Link reference http://stackoverflow.com/questions/19916845/cant-access-to-files-in-resources-directory-with-maven-with-eclipse-ide
public void getPath(){
try
{
File imageFile = new File(this.getClass().getResource(IMAGE_FILE).toURI());
//System.out.println("ImageFile is: "+ imageFile.toString()); //Output is the full path starting from C drive till the image
imageFileLength = (int) imageFile.length();
//System.out.println("Image File length : "+ imageFileLength);
imageStream = new FileInputStream(imageFile);
System.out.println("ImageStream is :"+ imageStream.read()); // Output is 255
}
catch (IOException e)
{
e.printStackTrace();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
//Now insert this image path in table bookInfo in imagePath column
conn = newConnection.dbConnection();
String insertImage = "Insert into bookInfo(availability,isbn,hardback,paperback,imagePath) values (?,?,?,?,?)";
try
{
statement = conn.createStatement();
preparedStatement = conn.prepareStatement(insertImage);
preparedStatement.setString(1, "yes");
preparedStatement.setInt( 2, 97815972);
preparedStatement.setString(3, "hardback");
preparedStatement.setString(4, "not paperback");
preparedStatement.setBinaryStream(5, imageStream, imageFileLength);
preparedStatement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
On executing this code, I was able to get a BLOB into database. I don't understand what does it mean by just storing reference of image path in database. Also, I have about 10 images in that folder. I need to get all of them inserted in the database. I think I am doing an extra step. I am first getting the image from the file "images" and then converting it to InputStream and storing it as BLOB in MySql. I am confused how should I go about approaching this problem. What should be the correct way of uploading image from a file to database. I am not asking user to upload anything, but just getting the image from database and displaying it to user on clicking of a link. Any help is appreciated. Thank You in advance.