Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am trying to display stored stream in mongodb GridFS as image in angularjs using webapi c#. I am using mongodb 2.4.4 in my project.
MongoDB Package : [^]

What I have tried:

I saved the stream from angular to mongodb using the below code.

C#
using (var stream = await this.Request.Content.ReadAsStreamAsync())
{
var database = this.imageManager.GetDatabase(); // get database object
var gridFsInfo = database.GridFS.Upload(stream, "FileName"); 
objectId = gridFsInfo.Id.ToString();
stream.Close();
}
return this.Ok(objectId);

The above code inserted new documents in fs.files and fs.chunk.
Now i need to display the uploaded image from mongodb GridFS to angularjs.
I tried the below code. But the image is showing as corrupted image.
C#
[HttpGet]
[Route("~/GetImageFromServer/{objectId}")]
public HttpResponseMessage GetImageFromMongo(string objectId)
{
var stream = this.GetImage(objectId);
HttpResponseMessage response = new HttpResponseMessage();
response.Content = stream;
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return response;
}

private StreamContent GetImage(string objectId)
{
var database = this.imageManager.GetDatabase();
var file = database.GridFS.FindOneById(new ObjectId(objectId));
var stream = file.OpenRead();
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
return new StreamContent(stream);
}


Below line should display the image as background image
HTML
<div class="thumb-hov thumbnail-item" [ngStyle]="{'background-image': 'url(' + ImageURL+''+wb.ImageId+ ')'}">


Thanks in advance
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900