将图像从URI上载到Azure BLOB

时间:2014-08-17 23:26:51

标签: asp.net asp.net-mvc asp.net-mvc-5 azure-storage-blobs

我想将图片从uri postet上传到asp.net mvc5控制器到azure blob存储。我已经使用HttpPostedFileBase了,就像这样。我可以以某种方式从图像uri获取内存流吗?

HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
var imgFile = System.Drawing.Image.FromStream(hpf.InputStream, true, true);
CloudBlockBlob blob = coversContainer.GetBlockBlobReference("img.jpg");
MemoryStream stream = new MemoryStream();
imgFile.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
blob.UploadFromStream(stream);

1 个答案:

答案 0 :(得分:0)

所以这就是我设法完成它的方法:

public static Image DownloadRemoteImage(string url)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (Exception)
    {
        return null;
    }

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK ||
        response.StatusCode == HttpStatusCode.Moved ||
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
    {
        // if the remote file was found, download it
        Stream inputStream = response.GetResponseStream();
        Image img = Image.FromStream(inputStream);
        return img;
    }
    else
    {
        return null;
    }
}

此代码段是根据此问题的答案拍摄并修改的: Download image from the site in .NET/C#