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

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

最佳答案

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);
}

关于mongodb - 想要将图像从给定的 URL 存储到 gridfs,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11588189/

10-16 12:08