Search code examples
c#azureazure-functionsazure-storage

Download and store file to Azure using Azure function


I want to download file from some third party server and wanted to store inside Azure Storage. But I want to perform this process using Azure function. Below are the steps I want to achieve.

  1. Create Azure(HTTP trigger enable)function what will be executed by third party server using WebHook.
  2. Download file content using download URL given by Webhook using "Webclient" in C#.
  3. Store file content into Azure Storage directly.

       
        Task.Run(() =>
        {
        using (var webClient = new WebClient())
        {
            webClient.Headers.Add(HttpRequestHeader.Authorization, string.Format("Bearer {0}", {download token}));
            webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
            webClient.DownloadFileAsync("https://www.server.com/file1.mp4", {Here I want to store file into Azure Storage});
            }
            });
        
        

Solution

  • You can put the file in the request body of the req like this, and then upload it to azure blob storage.

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    using Microsoft.WindowsAzure.Storage;
    
    namespace FunctionApp5
    {
        public static class Function1
        {
            [FunctionName("Function1")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                log.LogInformation("C# HTTP trigger function processed a request.");
    
                //Here is the keycode.
    
                //Connect to the Storage Account.
                var storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=bowmanimagestorage02;AccountKey=xxxxxxxfile.core.windows.net/");
                var myClient = storageAccount.CreateCloudBlobClient();
    
                //Here is the container name on portal.
                var container = myClient.GetContainerReference("test");
    
                //Here is the name you want to save as.
                var blockBlob = container.GetBlockBlobReference("something.txt");
    
                //Put the stream in this place.
                await blockBlob.UploadFromStreamAsync(req.Body);
    
    
                string name = req.Query["name"];
    
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;
    
                return name != null
                    ? (ActionResult)new OkObjectResult($"Hello, {name}")
                    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
            }
        }
    }
    

    Of course you can also pass in the data stream, the key code is the same.