Upload image to Azure Blob Storage from URL

crystyxn picture crystyxn · Nov 7, 2016 · Viewed 7.1k times · Source

Is it possible to have the CloudBlockBlob.UploadFromStreamAsync accept URL for images? I am trying to use the LinkedIn basicprofile api to retrieve the picture URL of the user (already have the URL) and I am trying to maybe download then upload the picture to the Azure Blob, like they selected a picture from their computer.

This is how it looks like now:

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>

The method in the controller:

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

Answer

Supraj V picture Supraj V · Nov 7, 2016

Below method uploads file(URL) to azure cloudblob

NOTE: Input for this method example

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){ ... }

}