mongodb 存储图片等文件有两种方式 (该文章针对的是已经可以使用mongodb整合spring的用户) 相关阅读: mongodb备份与恢复 http
mongodb 存储图片等文件有两种方式
(该文章针对的是已经可以使用mongodb整合spring的用户)
相关阅读:
mongodb备份与恢复
centos编译安装mongodb
centos 编译安装 mongodb与mongodb的php扩展
centos 6 使用 yum 安装mongodb及服务器端配置
ubuntu 13.04下安装mongodb2.4.3
如何在mongodb中建立新数据库和集合
mongodb入门必读(概念与实战并重)
《mongodb 权威指南》(mongodb: the definitive guide)英文文字版[pdf]
1.使用mongotemplate
/**
* 存储文件
* @param collectionname 集合名
* @param file 文件
* @param fileid 文件id
* @param companyid 文件的公司id
* @param filename 文件名称
*/
public void savefile(string collectionname, file file, string fileid, string companyid, string filename) {
try {
db db = mongotemplate.getdb();
// 存储fs的根节点
gridfs gridfs = new gridfs(db, collectionname);
gridfsinputfile gfs = gridfs.createfile(file);
gfs.put(aliases, companyid);
gfs.put(filename, fileid);
gfs.put(contenttype, filename.substring(filename.lastindexof(.)));
gfs.save();
} catch (exception e) {
e.printstacktrace();
system.out.println(存储文件时发生错误!!!);
}
}
// 取出文件
public gridfsdbfile retrievefileone(string collectionname, string filename) {
try {
db db = mongotemplate.getdb();
// 获取fs的根节点
gridfs gridfs = new gridfs(db, collectionname);
gridfsdbfile dbfile = gridfs.findone(filename);
if (dbfile != null) {
return dbfile;
}
} catch (exception e) {
// todo: handle exception
}
return null;
}
//抱歉项目案例不能给你,不过这个是向mongodb存取文件的实现代码,,希望能帮助到你。
//由gridfsdbfile 可以得到inputstream,这样你就明白了吧。
2.使用gridfstemplate
网上找到的第一种方法总结的非常的不好,spring结合的感觉不够紧密。 谷歌了下参考了下网上的文章。
参考文章
spring 伪配置
threads-allowed-to-block-for-connection-multiplier=100
connect-timeout=1000 max-wait-time=1500 auto-connect-retry=true
socket-keep-alive=true socket-timeout=1500 slave-ok=true
write-number=1 write-timeout=0 write-fsync=true />
password=*** mongo-ref=mongo />
db-factory-ref=mongodbfactory />
abstract=true>
java 伪代码
list files = this.getgridfstemplate().find(null); //查询全部,查询方式和mongotemplate一样
system.out.println(-----------------);
for (gridfsdbfile file: files) {
system.out.println(file);
}
mongodb 的详细介绍:请点这里
mongodb 的下载地址:请点这里