0
votes

I want to upload the upload a file to a storage location through URL using Azure function app from Azure blob storage. I'm able to pull the file from Azure blob. But not able to upload the file through url. Below I have attached the code which i have written. Could anyone help me on this?

#r "Newtonsoft.Json"
#r "Microsoft.WindowsAzure.Storage"
#r "System.IO"


using System;
using System.IO;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Auth;
using System.Xml;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net;

public static void Run(string input, TraceWriter log)
{
        log.Info($"C# manual trigger function processed\n");
        const string StorageAccountName = "";
        const string StorageAccountKey = "";

        var storageAccount = new CloudStorageAccount(new StorageCredentials(StorageAccountName, StorageAccountKey), true);
        var blobClient = storageAccount.CreateCloudBlobClient();
        var container = blobClient.GetContainerReference("hannahtest");
        var Destcontainer = blobClient.GetContainerReference("hannahtestoutput");
        var blobs = container.ListBlobs();
        log.Info($"Creating Client and Connecting");
        foreach (IListBlobItem item in container.ListBlobs(null, false))
        {

               if (item is CloudBlockBlob blockBlob)
               {
                    using (StreamReader reader = new StreamReader(blockBlob.OpenRead())                                     
                    {
                        //old content string will read the blockblob (xml)till end 
                        string oldContent1 = reader.ReadToEnd();    
                        log.Info(oldContent1);

                        var content = new FormUrlEncodedContent(oldContent1);

                        var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

                        var responseString = await response.Content.ReadAsStringAsync();
                        log.Info($"Success");
                    }
                }
         }
}
2
Do you want to upload your blob to Destcontainer or http://www.example.com/recepticle.aspx, like a web app?Jerry Liu
I need to upload the blob into example.com/recepticle.aspx. ThanksSreepu
What error message do you get? Have you programmed in that web app to accept this post request?Jerry Liu
I am new to this. Could you please let me know if you have any sample reference that will upload a file into a URL? if yes, could you please share it. I can use that as a reference and build my code and get back to you .Sreepu

2 Answers

0
votes

Have a look at Blob Output Binding - that's how the blobs are intended to be uploaded from Azure Functions, without messing with Azure Storage SDK.

0
votes

Azure function to upload multiple image file to blob storage.

  • using Microsoft.WindowsAzure.Storage.Auth;
  • using Microsoft.WindowsAzure.Storage;
  • using Microsoft.WindowsAzure.Storage.Blob;

    public static class ImageUploadFunction
    {
        [FunctionName("ImageUploadFunction")]
        public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post")]HttpRequestMessage req, ILogger log)
        {
    
            var provider = new MultipartMemoryStreamProvider();
            await req.Content.ReadAsMultipartAsync(provider);
            var files = provider.Contents;
            List<string> uploadsurls = new List<string>();
            foreach (var file in files) {
                var fileInfo = file.Headers.ContentDisposition;
                Guid guid = Guid.NewGuid();
                string oldFileName = fileInfo.FileName;
                string newFileName = guid.ToString();
                var fileExtension = oldFileName.Split('.').Last().Replace("\"", "").Trim();
                var fileData = await file.ReadAsByteArrayAsync();
                try {
                    //Upload file to azure blob storage method
                    var upload = await UploadFileToStorage(fileData, newFileName + "." + fileExtension);
                    uploadsurls.Add(upload);
                }
                catch (Exception ex) {
                    log.LogError(ex.Message);
                    return new BadRequestObjectResult("Somthing went wrong.");
                }
            }
            return uploadsurls != null
                  ? (ActionResult)new OkObjectResult(uploadsurls)
                   : new BadRequestObjectResult("Somthing went wrong.");                 
        }
        private static async Task<string> UploadFileToStorage(byte[] fileStream, string fileName)
        {
            // Create storagecredentials object by reading the values from the configuration (appsettings.json)
            StorageCredentials storageCredentials = new StorageCredentials("<AccountName>", "<KeyValue>");
    
            // Create cloudstorage account by passing the storagecredentials
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
    
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
            // Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
            CloudBlobContainer container = blobClient.GetContainerReference("digital-material-library-images");
    
            // Get the reference to the block blob from the container
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
    
            // Upload the file
            await blockBlob.UploadFromByteArrayAsync(fileStream,0, fileStream.Length);
    
            blockBlob.Properties.ContentType = "image/jpg";
            await blockBlob.SetPropertiesAsync();
    
            return blockBlob.Uri.ToString();
            //return await Task.FromResult(true);
        }
    
    
    }