Home > Software design >  UploadFromByteArrayAsync not saving extension with file name in Azure Blob storage in asp.net core
UploadFromByteArrayAsync not saving extension with file name in Azure Blob storage in asp.net core

Time:03-31

I am saving a document byte array to azure blob but I discovered that the extension is not saved. After the file is saved the full name of the file is returned with the extension. I expect that when I click on the link the file should open in the browser but instead I got..

<Error>
<Code>ResourceNotFound</Code>
<Message>The specified resource does not exist. RequestId:6012e9b1-901e-011b-57e9-447dc0000000 Time:2022-03-31T10:21:29.3337046Z</Message>
</Error>

   public async Task<string> UploadFileToBlobAsync(string strFileName, byte[] fileData, string fileMimeType)
        {
            var accessKey = _configuration.GetValue<string>("ConnectionStrings:AzureBlob");
            CloudStorageAccount csa = CloudStorageAccount.Parse(accessKey);
            CloudBlobClient cloudBlobClient = csa.CreateCloudBlobClient();
            string containerName = "api-v2-files"; //Name of your Blob Container
            CloudBlobContainer cbContainer = cloudBlobClient.GetContainerReference(containerName);

            if (await cbContainer.CreateIfNotExistsAsync())
            {
                await cbContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
            }

            if (strFileName != null && fileData != null)
            {
                CloudBlockBlob cbb = cbContainer.GetBlockBlobReference(strFileName);
                cbb.Properties.ContentType = fileMimeType;
                await cbb.UploadFromByteArrayAsync(fileData, 0, fileData.Length);
                return cbb.Uri.AbsoluteUri;
            }
            return "";
        }

CodePudding user response:

The issue is with the following line of code:

if (await cbContainer.CreateIfNotExistsAsync())
{
    await cbContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
}

Basically your code is not going into if block if the container is already exists in your storage account. Because of this, your container's access level is not changed.

Assuming you are using version 11 of the SDK, please use the following override of CreateIfNotExists: CreateIfNotExistsAsync(BlobRequestOptions, OperationContext, CancellationToken).

  • Related