2014-02-16 36 views
0

我有一个Web服务,它接收一个canvas标签的内容并将其保存到MongoDB GridFS存储中。在MongoDB GridFS中保存一个base 64编码图像

下面的代码工作,但它需要将图像保存到磁盘,然后将其发送到MongoDB。

Using postBody As Stream = Request.InputStream 
     ' Get the body of the HTTP POST (the data:image/png) 
     postBody.Seek(0, SeekOrigin.Begin) 
     Dim imageData As String = New StreamReader(postBody).ReadToEnd 

     Dim base64Data = Regex.Match(imageData, "data:image/(?<type>.+?),(?<data>.+)").Groups("data").Value 
     Dim data As Byte() = Convert.FromBase64String(base64Data) 

     Using stream = New MemoryStream(data, 0, data.Length) 
      Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(stream) 

      Dim directory = Server.MapPath("~/App_Data/temp/") 
      Dim file = String.Concat(directory, id, ".png") 
      img.Save(file, System.Drawing.Imaging.ImageFormat.Png) 

      Using fs = New FileStream(file, FileMode.Open) 
       db.GridFS.Upload(fs, id & ".png") 
      End Using 

     End Using 
    End Using 

有没有更好的方法,或许在上传到MongoDB之前不需要将其保存到磁盘?

+0

为什么不只是传递它的内存流,'位置'设置回'0'? – WiredPrairie

回答

0

正如评论中所建议的,只需使用作为参数Upload而不是写出到文件。

而且也注意到,您不必转换,以通过发送GridFS的(为此事或纯蒙戈场)文件为Base64。输入可以是二进制的,除非你当然需要希望你的数据base64编码为了你的方便。

相关问题