Because the document structure of MongoDB is in the Bjson format (bjson full name: Binary JSON), and the Bjson format itself supports data in binary format, you can save the data in binary format of the file directly into the MongoDB document structure. However, because the maximum length of a bjson cannot exceed 4M, it limits the maximum number of files that can be deposited in a single document beyond 4M. To provide support for bulk file access, the Samus driver provides a "GRIDFS" approach to support, and "Gridfs" mode file operations require the introduction of a new assembly "MongoDB.GridFS.dll". Here are two ways to implement each.
First, access files in the Document object
When the file size is small, directly into the document object to achieve more concise. For example, a large number of image file access, general picture files will not exceed 4M. We first implement an upload image into the database, and then take out to write back to the page example:
1. Save the picture in the BjsonCopy Code code as follows:
2. Get image byte data stored in Bjson modeCopy Code code as follows:
The above two pieces of code are two methods added to the BLL encapsulation class for MONGODB related operations to encapsulate the contents of the previous section. Here's a look at how to call in WebForm:
In the interface drag out a FileUpload control and a button control, page CS class plus the following methods:Copy Code code as follows:
Second, the use of Gridfs way to access files
Before realizing the Gridfs way, I'll talk about its principle and why I can save large files. The driver first creates two collections in the current database: the "Fs.files" and "Fs.chunks" collections, which record file names, file creation times, file types, and other basic information, which blocks the binary data of the file (and supports encrypting the binary data). Chunking means dividing a file by a specified size and then depositing it into multiple documents. How does "fs.files" know which chunk of its corresponding file binary data is? That is because there is a "files_id" key in "Fs.chunks", which corresponds to the "_id" of "fs.files". "Fs.chunks" also has a key (int type) "n", which indicates the order of the blocks. The "FS" in the two collection names can also be customized by parameters.
If you just want to know how to use, you can ignore the above paragraph, the following will use:
1. Gridfs Way of File New, read, deleteCopy Code code as follows:
2. Encapsulates the Gridfs operation again, the new document only stores the file name, equivalent to just a key, the new document can also have other than "filename" other keys.Copy Code code as follows:
File access should not be difficult, it is worth noting that when you read binary data from a document in the first way, be sure to convert the type to the "Binary" type, and the system's own key "_id", which is not a string type, is "Oid" type.
Author: Lee (Lipan)
Source: [Lipan] (http://www.cnblogs.com/lipan/)