Store PDF into MongoDB with C# REST API and Display in Angular 6 Web App

Gul Ershad
3 min readDec 14, 2018

Introduction

MongoDB is an outstanding NoSQL database for the unstructured data and provides more performance out of the system by eliminating lots of stuff like log shipping, referential integrity that Relational Database System (RDBMS) enforces by default. It can store different types of data like binary, stream, JSON, text, etc.

Architecture to Store PDF into MongoDB and Display on Angular 6

MongoDB can store files like PDF, MS-Excel, Word, etc. either in the form of Binary or Stream.

Below Architecture Diagram:

Figure: Store PDF File in MongoDB by using GridFS

Structure and Storage Create by GridFs in MongoDB

GridFs creates two entery into the Database after File upload in the form of Stream or Binary:

  • fs.Files : It stores information like File Name, Chunk Size, Upload Date, etc.
  • fs.Chunks: File Stream or Binary is divided into chunks and stored in this collection.

GridFs creates the below structure into MongoDB:

Figure: File and Chunks related Information
Figure: Chunks Details

NuGet Package

Install the below package for the GridFS and MongoDB:

  • MongoDB.Driver
  • MongoDB.Driver.GridFS

Server-Side Implementation

Data Manager Implementation:

Upload from Stream:

public ObjectId UploadFromStreamAsync(string fileName, Stream stream){//mongoDbDatabase : get database of MongoDb by establishing //connectionvar gridFsBucket = new GridFSBucket(mongoDbDatabase);
var task = Task.Run(() => gridFsBucket.UploadFromStreamAsync(fileName, stream));
return task.Result;
}

Download from Stream:

public async Task<GridFSDownloadStream> DownloadFromStream(string fileName){//mongoDbDatabase: establish connection from mongodb and get //Databese
var gridFsBucket = new GridFSBucket(mongoDbDatabase);
var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, fileName);var finData = await gridFsBucket.FindAsync(filter);var firstData = finData.FirstOrDefault();var bsonId = firstData.Id;var dataStream = await gridFsBucket.OpenDownloadStreamAsync(bsonId);return dataStream;}

Service Layer Implementation:

[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "save_file?fileName={fileName}")]
short SaveFile(string fileName, Stream stream);
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json, UriTemplate = "get_file?fileName={fileName}")]
Stream GetFile(string fileName);

App.config Configuration:

<service behaviorConfiguration="MyFileService.file" name="MyFileService"><endpoint address=""binding="webHttpBinding"contract="MyService.IFileService"bindingConfiguration="MyService.FileService"behaviorConfiguration="web"/><host><baseAddresses><add baseAddress="http://localhost:9001/file/"/></baseAddresses></host></service>

Buffer Size Configuration:

<bindings><webHttpBinding><binding name="MyFileService.File"

Conclusion

Rather than storing a file in a single document, GridFS splits the file into parts or chunks, and stores each chunk as a separate document. By default, GridFS uses a default chunk size of 255 kB; that is, GridFS breaks a file into chunks of 255 kB with the exception of the last chunk. The last chunk is only as large as required. Furthermore, files that are no larger than the chunk size only have a final chunk, using only as much space as needed plus some extra metadata.

--

--

Gul Ershad

A technology explorer with the drive to learn, apply and expand his mind.