I want to know specifically about saving an object with an image inside it. What I want to do is saving an entire object with image inside it, Image must be saved. I tried this but it saves only File instance with file path. Its not saving the image. Any help would be appreciated. Thank you. Here is my code for saving an object but its saving a file instance instead of an image.
import java.io.File;
import org.springframework.data.mongodb.core.mapping.Document;
import com.discusit.model.Artwork;
@Document(collection="Artwork")
public class ArtworkImpl implements Artwork {
private String artworkName;
private String artworkVersion;
private String fileName;
private File file;
public ArtworkImpl() {
}
public ArtworkImpl(String name, String version, String fileName, File file) {
this.artworkName = name;
this.artworkVersion = version;
this.fileName = fileName;
this.file = file;
}
public String getArtworkName() {
return artworkName;
}
public void setArtworkName(String artworkName) {
this.artworkName = artworkName;
}
public String getArtworkVersion() {
return artworkVersion;
}
public void setArtworkVersion(String artworkVersion) {
this.artworkVersion = artworkVersion;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
Here is my main method :- NOTE : Main method works fine, but not saving image, instead saving file instance.
public class MainApplication {
public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(SpringMongoConfig.class);
GridFsOperations gridOperations =
(GridFsOperations) ctx.getBean("gridFsTemplate");
DBObject metaData = new BasicDBObject();
metaData.put("extra1", "anything 1");
metaData.put("extra2", "anything 2");
InputStream inputStream = null;
try {
inputStream = new FileInputStream("/home/discusit/Downloads/birds.jpg");
gridOperations.store(inputStream, "birds.jpg", "image/jpg", metaData);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
I want to save object with image.
UPDATE : I did this but by converting an image to byte array and fetching byte array and converting back to Image, just want to know is there any other way by which I can save an image directly in mongoDB but without converting it to byte array ????