今天主要是说一下MongoDB如何存储和上传物理文件,即MongoDB GridFS功能.
GridFS是MongoDB中的一个内置功能,可以用于存放大量小文件,MongoDB同样提供了命令来操作GridFS.
1、首先启动MongoDB服务
2、再打开一个CMD窗口,输入mongofiles list -d tang
参数说明:
-d 指定数据库
-u –p 指定用户名,密码
-h 指定主机
-port 指定主机端口
-c 指定集合名,默认是fs
-t 指定文件的MIME类型,默认会忽略
大家可以看到在tang这个database中有8个文件,并将Filename列出来.另外可以通过MongoVUE工具可以更详细的看到这些文件.
3、查找文件:
mongofiles list xxx //会查找所有文件名以"xxx"为前缀的文件
mongofiles search xxx //会查找所有文件名中包含"xxx"的文件
上传一个文件:
mongofiles put xxx.txt
下载一个文件:
mongofiles get xxx.txt
后面再上两个GridFS读写方法,客户端软件用的是samus-mongodb.
public void MongoGridFsUpload(byte[] byteFile, string fileName, string dataBaseName)
{
var MongoConfigurationBuilder = new MongoConfigurationBuilder();
MongoConfigurationConnection(MongoConfigurationBuilder);
using (IMongo mongo = new Mongo(MongoConfigurationBuilder.BuildConfiguration()))
{
mongo.Connect();
IMongoDatabase dataBase = mongo.GetDatabase(dataBaseName);
GridFile fs = new GridFile(dataBase); //这里GridFile构造函数有个重载,bucket参数就是用来替换那个创建集合名中默认的"fs"的.
GridFileStream gfs = fs.Create(fileName);
gfs.Write(byteFile, 0, byteFile.Length);
gfs.Close();
gfs.Dispose();
}
}
public void MongoGridFsRead(string fileName, string dataBaseName)
{
var MongoConfigurationBuilder = new MongoConfigurationBuilder();
MongoConfigurationConnection(MongoConfigurationBuilder);
using (IMongo mongo = new Mongo(MongoConfigurationBuilder.BuildConfiguration()))
{
IMongoDatabase dataBase = mongo.GetDatabase(dataBaseName);
GridFile fs = new GridFile(dataBase);
GridFileStream gfs = fs.OpenRead(fileName);
Byte[] buffer = new Byte[gfs.Length];
//需要读的数据长度
long dataToRead = gfs.Length;
int length;
while (dataToRead > 0)
{
//检查客户端是否还处于连接状态
if (System.Web.HttpContext.Current.Response.IsClientConnected)
{
length = gfs.Read(buffer, 0, 10000);
System.Web.HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
System.Web.HttpContext.Current.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//如果不再连接则跳出死循环
dataToRead = -1;
}
}
gfs.Close();
gfs.Dispose();
}
}








浙公网安备 33010602011771号