我想具体了解保存其中包含图像的对象。我想要做的是保存一个包含图像的整个对象,必须保存图像。我试过这个,但它只保存带有文件路径的文件实例。它不保存图像。任何帮助,将不胜感激。谢谢你。这是我保存对象的代码,但它保存的是文件实例而不是图像。
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;
}
}
这是我的主要方法:- 注意:主要方法工作正常,但不保存图像,而是保存文件实例。
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");
}
}
我想用图像保存对象。
更新:我这样做了,但是通过将图像转换为字节数组并获取字节数组并转换回图像,只是想知道有没有其他方法可以直接在 mongoDB 中保存图像但不将其转换为字节数组? ???