4

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

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

4

1 回答 1

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);
}
于 2012-07-21T13:17:35.040 回答