int gridfs_store_buffer( gridfs *gfs, const char *data, gridfs_offset length, const char *remotename, const char *contenttype ) { char const *end = data + length; const char *data_ptr = data; bson_oid_t id; int chunkNumber = 0; int chunkLen; bson *oChunk; /* Large files Assertion */ assert( length <= 0xffffffff ); /* Generate and append an oid*/ bson_oid_gen( &id ); /* Insert the file's data chunk by chunk */ while ( data_ptr < end ) { chunkLen = DEFAULT_CHUNK_SIZE < ( unsigned int )( end - data_ptr ) ? DEFAULT_CHUNK_SIZE : ( unsigned int )( end - data_ptr ); oChunk = chunk_new( id, chunkNumber, data_ptr, chunkLen ); mongo_insert( gfs->client, gfs->chunks_ns, oChunk ); chunk_free( oChunk ); chunkNumber++; data_ptr += chunkLen; } /* Inserts file's metadata */ return gridfs_insert_file( gfs, remotename, id, length, contenttype ); }
int gridfs_store_file( gridfs *gfs, const char *filename, const char *remotename, const char *contenttype ) { char buffer[DEFAULT_CHUNK_SIZE]; FILE *fd; bson_oid_t id; int chunkNumber = 0; gridfs_offset length = 0; gridfs_offset chunkLen = 0; bson *oChunk; /* Open the file and the correct stream */ if ( strcmp( filename, "-" ) == 0 ) fd = stdin; else { fd = fopen( filename, "rb" ); if (fd == NULL) return MONGO_ERROR; } /* Generate and append an oid*/ bson_oid_gen( &id ); /* Insert the file chunk by chunk */ chunkLen = fread( buffer, 1, DEFAULT_CHUNK_SIZE, fd ); do { oChunk = chunk_new( id, chunkNumber, buffer, chunkLen ); mongo_insert( gfs->client, gfs->chunks_ns, oChunk, NULL ); chunk_free( oChunk ); length += chunkLen; chunkNumber++; chunkLen = fread( buffer, 1, DEFAULT_CHUNK_SIZE, fd ); } while ( chunkLen != 0 ); /* Close the file stream */ if ( fd != stdin ) fclose( fd ); /* Large files Assertion */ /* assert(length <= 0xffffffff); */ /* Optional Remote Name */ if ( remotename == NULL || *remotename == '\0' ) { remotename = filename; } /* Inserts file's metadata */ return gridfs_insert_file( gfs, remotename, id, length, contenttype ); }
bson gridfile_writer_done( gridfile* gfile ) { /* write any remaining pending chunk data. * pending data will always take up less than one chunk */ bson* oChunk; if( gfile->pending_data ) { oChunk = chunk_new(gfile->id, gfile->chunk_num, gfile->pending_data, gfile->pending_len); mongo_insert(gfile->gfs->client, gfile->gfs->chunks_ns, oChunk); chunk_free(oChunk); free(gfile->pending_data); gfile->length += gfile->pending_len; } /* insert into files collection */ return gridfs_insert_file(gfile->gfs, gfile->remote_name, gfile->id, gfile->length, gfile->content_type); }