- BSONObj GridFS::storeFile( const char* data , size_t length , const string& remoteName , const
- string& contentType) {
- char const * const end = data + length; //获取文件末尾指针
- OID id;
- id.init();
- BSONObj idObj = BSON("_id" << id); //生成唯一id
- int chunkNumber = 0;
- while (data < end) {
- //这里_chunkSize = DEFAULT_CHUNK_SIZE = 256 * 1024;
- //根据实际文件大小得到ChunkSize
- int chunkLen = MIN(_chunkSize, (unsigned)(end-data));
- //这里chunkNumber为文件的第几个chunk
- GridFSChunk c(idObj, chunkNumber, data, chunkLen);
- //向fs.chunks这个collection中插入document
- _client.insert( _chunksNS.c_str() , c._data );
- chunkNumber++;
- data += chunkLen;
- }
- //向fs.files这个collection中插入文件相关信息
- return insertFile(remoteName, id, length, contentType);
- }
在读取文件的时候, 在fs.files中根据文件名和最新上传时间找到最新的一个文件记录, 然后取出"_id", 根据"_id"到fs.chunks中查找"files_id"为"_id"的chunk, 并按"n"进行排序,然后读取chunk中"data"中的数据.
文件删除:
- GridFile::GridFile( GridFS * grid , BSONObj obj ) {
- _grid = grid;
- _obj = obj;
- }
- GridFile GridFS::findFile( const string& fileName ) {
- return findFile( BSON( "filename" << fileName ) );
- };
- GridFile GridFS::findFile( BSONObj query ) {
- //_client为DBClientBase对象, 去fs.files这个集合去query数据.
- query = BSON("query" << query << "orderby" << BSON("uploadDate" << -1));
- // 返回GridFile的对象
- return GridFile( this , _client.findOne( _filesNS.c_str() , query ) );
- }
- GridFS进行删除文件也是对fs.files和fs.chunks进行删除操作.
- void GridFS::removeFile( const string& fileName ) {
- auto_ptr<DBClientCursor> files = _client.query( _filesNS , BSON( "filename" << fileName ) );
- while (files->more()) {
- BSONObj file = files->next();
- BSONElement id = file["_id"];
- _client.remove( _filesNS.c_str() , BSON( "_id" << id ) );
- _client.remove( _chunksNS.c_str() , BSON( "files_id" << id ) );
- }
- }
PS:
- int chunkLen = MIN(_chunkSize, (unsigned)(end-data));
