从URL上传图像到Azure Blob Storage

本文关键字:Azure Blob Storage 图像 URL | 更新日期: 2023-09-27 18:16:50

是否可以让CloudBlockBlob.UploadFromStreamAsync接受图像的URL ?我正在尝试使用LinkedIn基本配置api来检索用户的图片URL(已经有URL),我正在尝试下载然后将图片上传到Azure Blob,就像他们从计算机中选择了一张图片一样。

现在的样子:

using (Html.BeginForm("UploadPhoto", "Manage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
      <div class="browseimg">
          <input type="file" class="display-none" name="file" id="files" onchange="this.form.submit()" />
      </div>
 }
 <button class="btn btn-primary width-100p main-bg round-border-bot" id="falseFiles">
       Upload billede
 </button>

控制器中的方法:

public async Task<ActionResult> UploadPhoto(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {
        var fileExt = Path.GetExtension(file.FileName);
        if (fileExt.ToLower().EndsWith(".png") 
             || fileExt.ToLower().EndsWith(".jpg") 
             || fileExt.ToLower().EndsWith(".gif"))
        {
            var user = await GetCurrentUserAsync()
            await service.Upload(user.Id, file.InputStream);
        }
   }
    return RedirectToAction("Index")
}

从URL上传图像到Azure Blob Storage

下面的方法上传文件(URL)到azure cloudblob

注:输入此方法示例

file="http://example.com/abc.jpg" and ImageName="myimage.jpg";

public static void UploadImage_URL(string file, string ImageName)
{
    string accountname = "<YOUR_ACCOUNT_NAME>";
    string accesskey = "<YOUR_ACCESS_KEY>";
    try
    {
        StorageCredentials creden = new StorageCredentials(accountname, accesskey);
        CloudStorageAccount acc = new CloudStorageAccount(creden, useHttps: true);
        CloudBlobClient client = acc.CreateCloudBlobClient();
        CloudBlobContainer cont = client.GetContainerReference("<YOUR_CONTAINER_NAME>");
        cont.CreateIfNotExists();
        cont.SetPermissions(new BlobContainerPermissions
        {
            PublicAccess = BlobContainerPublicAccessType.Blob
        });
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(file);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream inputStream = response.GetResponseStream();
        CloudBlockBlob cblob = cont.GetBlockBlobReference(ImageName);
        cblob.UploadFromStream(inputStream);
    }
    catch (Exception ex){ ... }
}

看起来我所需要的只是一个简单的

 WebClient wc = new WebClient();
 MemoryStream stream = new MemoryStream(wc.DownloadData("https://media.licdn.com/mpr/..."));

await service.Upload(user.Id, stream);