想要将图像存储到给定URL的gridfs

时间:2012-07-20 23:31:11

标签: mongodb mongodb-.net-driver gridfs

是否可以直接将图像存储到mongo GridFS中,这是我从API获得的?或者我必须在本地存储然后将其插入mongo?

我试图直接从URL插入,但C#驱动程序给了我一个不支持URI的错误..

1 个答案:

答案 0 :(得分:6)

MongoGridFS类实现了.NET的流API,因此您应该能够使用MemoryStream来保存Web响应并插入到GridFS中。

try
{
    var server = MongoServer.Create("mongodb://192.168.1.8:27017/imgdb?safe=true");
    var db = server.GetDatabase("imgdb");

    string fileName = "logo-mongodb.png";

    // Get image from URL or API    
    WebRequest req = WebRequest.Create("http://media.mongodb.org/" + fileName);
    WebResponse response = req.GetResponse();
    Console.WriteLine("Response length is " + response.ContentLength + " bytes");

    // Copy from WebResponse to MemoryStream
    MemoryStream memStream;
    using (Stream responseStream = response.GetResponseStream())
    {
        memStream = new MemoryStream();

        byte[] buffer = new byte[1024];
        int byteCount;
        do
        {
            byteCount = responseStream.Read(buffer, 0, buffer.Length);
            memStream.Write(buffer, 0, byteCount);
        } while (byteCount > 0);
        responseStream.Close();
    }

    // Reset to beginning of stream
    memStream.Seek(0, SeekOrigin.Begin);

    // Save to GridFS    
    var gridFsInfo = db.GridFS.Upload(memStream, fileName);

    // Success!
    Console.WriteLine("Success!");
}
catch (Exception err)
{
    Console.WriteLine("Something went wrong: "+err.Message);
}