Storing and Retrieving image from the MongoDB (GridFs) and displaying in Html using vb.net webservice

StackOverflow https://stackoverflow.com/questions/21496096

  •  05-10-2022
  •  | 
  •  

Question

I am trying to store and retrieve images from the MongoDB (Gridfs) and displaying the image using HTML.

I stored the image and got the image id, on passing the id into the HTML page using Ajax it takes the image id but image is not getting displayed can any one please guide me.

Here is my code:

HTML code:

 <html>
 <head>
 </head>
   function display() {
      $.ajax({
          type: 'POST',
          url: 'xidirectorywebservice.asmx/UploadImage',

      data: "{ }",

          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          success: function (image_string) 
             {
             var data = 'data:image/png;base64,' + image_string.d;
              var icon_elem = document.getElementById("ItemPreview");  //adding img id
              icon_elem.src = data;
             $(document.body).append(image_string.d);
            },
          error: function () {
              alert("Error");
          }

      });

      }

  </script>

 </head>
 <body  onload="display()">
 <img id="ItemPreview" src=""  />
 </body>
 </html>

vb.net (Webservice) code:

XIImage class:

Imports MongoDB.Bson
Public Class XIImage

Public Property _id As ObjectId
Public Property name As String = ""
Public Property title As String = ""
Public Property image As Byte()
Public Property ImageId() As ObjectId
End Class

Code:

 Public Function UploadImage() As String 
    Dim server As MongoServer = MongoServer.Create("mongodb://localhost")
    Dim db As MongoDatabase = server("imagedemo")

    Dim collection As MongoCollection = db("demo")

    Dim imageBook As New XIImage
    imageBook._id = New ObjectId()
    imageBook.name = "Tom Sawyer"
    imageBook.title = "Content of the book goes here"
    imageBook.image = file.ReadAllBytes("C:\Users\Prog23\Desktop\wallpapers-41.jpg")

    Dim memoryStream As Stream = New MemoryStream(imageBook.image)
    Dim gfsi As MongoGridFSFileInfo = db.GridFS.Upload(memoryStream, imageBook.name)
    imageBook.ImageId = gfsi.Id.AsObjectId
    collection.Insert(imageBook)
    Dim id As New ObjectId(imageBook.ImageId.ToString())
    Dim sfile As MongoGridFSFileInfo = db.GridFS.FindOne(Query.EQ("_id", id)  

    Using stream = sfile.OpenRead()
        Dim sid = sfile.Id
        MsgBox(sid.ToString())
    End Using
    End Function

But when I query in shell prompt I can see the binary format of the image,Any help will be appreciated. cheers.

Was it helpful?

Solution

Your code is only getting the _id from the uploaded image and not the content. What you need is the content. I found a reference already on Stack overflow, to save me some typing. The code is C# but all the classes are the same as it is the same driver.

A quick disclaimer if I may. Unless your files are huge ( > 16MB [encoded] ) and which I'm guessing they are not, GridFS may not be your best option. You will likely find more joy and less jumping through hoops if you simply encode the uploaded file as base64 and insert it as a field just as you would with any regular MongoDB document. As such you'll find this easier to deal with.

GridFS is not magic, it is essentially just a client implementation of doing exactly that prior step, but dealing with the data in smart chunks in order to overcome the 16MB limitation on a BSON document. Read more on the links:

http://docs.mongodb.org/manual/core/gridfs/

http://docs.mongodb.org/manual/faq/developers/#faq-developers-when-to-use-gridfs

That said, on with it: So basically you want to read from the stream returned from .OpenRead() on the returned object and encode the output with base64 encoding.

As an alternate approach to in-lining the image in this way, you could pass the binary data into the response from another controller responding to images by a certain id or name. Your ajax upload then need only return the url to the image (controller end point with image id) and that would be a standard img src attribute.

It is also worthwhile to include some magic to detect the MIME type rather than hardcode that into your script.

OTHER TIPS

this is solution for that:

Display image from binary data in html

write this way:

<img src="data:image/jpeg;base64{binary data}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top