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.