我正在尝试从mongodb(gridfs)中存储和检索图像,并使用html显示图像。
我存储了图像并获得了图像ID,使用Ajax将ID传递到HTML页面时,它将采用图像ID,但未显示图像可以指导我。
这是我的代码:
html代码:
<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)代码:
xiimage类:
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
代码:
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:UsersProg23Desktopwallpapers-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
但是,当我在shell提示中查询时,我可以看到图像的二进制格式,将不胜感激。欢呼。
您的代码仅从上传的图像而不是内容中获取_id。您需要的是内容。我在堆栈溢出上找到了一个参考,以节省一些打字。代码是C#,但所有类都与同一驱动程序相同。
如果可以的话,快速免责声明。除非您的文件很大(> 16MB [编码]),并且我猜它们不是,否则GRIDFS可能不是您的最佳选择。如果您简单地将上传的文件作为base64编码上传的文件,然后像使用任何常规的mongoDB文档一样将其插入字段,那么您可能会发现更多的欢乐,而越来越少。因此,您会发现这更容易处理。
gridfs不是魔术,它本质上只是客户实现,即确切地执行以前的步骤,而是处理智能块中的数据,以克服BSON文档上的16MB限制。阅读有关链接的更多信息:
http://docs.mongodb.org/manual/core/gridfs/
http://docs.mongodb.org/manual/faq/developers/#faq-developers-when-to-use-use-gridfs
也就是说:因此,基本上,您想从返回对象上的 .openread()返回的流中读取并用base64编码对输出进行编码。
作为以这种方式将图像融入图像的另一种方法,您可以将二进制数据传递到另一个控制器的响应中,该控制器通过某个ID或名称响应图像。然后,您的AJAX上传只需要将URL返回到图像(带有图像ID的控制器终点),这将是标准的IMG SRC属性。
也值得包括一些魔术来检测MIME类型而不是将其用于脚本中的硬码。
这是解决方案:
从HTML中的二进制数据显示图像
以这种方式写:
<img src="data:image/jpeg;base64{binary data}" />