Uploading File to Azure Storage

923 Views Asked by At

I am trying to upload a byte array or binary file to Azure File Storage. Might be silly, but I am wondering how to pass in the http request body using clean architecture.

UploadToAzureApi.cs

[FunctionName("UploadToAzureApi")]
public Task Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req)
{
    _log.LogInformation("C# HTTP trigger function processed a request.");

    string filename = "TestFile";
    string directory = "sampleDirectory";
    string shareName = "sampleFileShare";

    var result = _application.UploadToAzure(filename,directory,shareName);

    return Task.FromResult(new OkObjectResult(result));
}

AzureUploadApplication.cs

 public Task UploadToAzure(string sFilename, string dir, string share)
        {
            // Retrieve the connection string from the config file
            string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");

            var shareName = share;
            var dirName = dir;
            var fileName = sFilename;

            // Create a new ShareClient
            ShareClient client = new ShareClient(connectionString, shareName);

            // Get the directory reference
            ShareDirectoryClient directory = client.GetDirectoryClient(dirName);

            // Try to create a new file
            ShareFileClient fileClient = directory.CreateFile(fileName, int.MaxValue);

            string filecontent = "Test";

            if (filecontent != null)
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(filecontent);

                // Upload the file
                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    //stream.Position = 0;
                    fileClient.UploadAsync(stream);
                    stream.Close();
                }
            }

            return Task.CompletedTask;
        }
1

There are 1 best solutions below

0
On

I have used the below code snippet to upload the Byte Array information to Azure File Storage.

Using post method, I am uploading from local and convert the file content into Byte Array and uploaded the Byte Array Information into Azure Blob Storage

var file = req.Form.Files["File"];
var filecontent = file.OpenReadStream();
var blobClient = new BlobContainerClient(Connection, containerName);
var blob = blobClient.GetBlobClient(file.FileName);
byte[] byteArray = Encoding.UTF8.GetBytes(filecontent.ToString());
using (Stream myblob = new MemoryStream(byteArray))
{
    await blob.UploadAsync(myblob);
}

Result

enter image description here

In azure enter image description here