'How do I store a picture in azure blob storage in asp.net mvc application?

I am currently working on an ASP.Net application that stores student information. I am required to store the following information:

  • Student number
  • Name
  • Email address
  • Home address
  • Contact no.
  • Upload photo of the student
  • isActive flag to state whether the student is active or not

This information is being stored in a document database and the photo of the student needs to be uploaded to Azure blob storage while returning the link of the image to the document database

How do I do this?

I currently have a class for the student information which looks like this :

public class Student
{
    [Key]
    public int StudentId { get; set; }

    [Required]
    [StringLength(8, MinimumLength = 8)]
    [DisplayName("Student Number")]
    public string StudentNo { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 1)]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 1)]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [DisplayName("Email Address")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, MinimumLength = 5)]
    [DataType(DataType.MultilineText)]
    [DisplayName("Home Address")]
    public string HomeAddress { get; set; }

    [Required]
    [DataType(DataType.PhoneNumber)]
    [StringLength(10)]
    [DisplayName("Mobile No.")]
    public string Mobile { get; set; }

    public bool IsActive { get; set; }
}

I have a separate view model for the blob as I was still experimenting with blobs:

 public class BlobViewModel
{

    public string BlobContainerName { get; set; }
    public string StorageUri { get; set; }
    public string ActualFileName { get; set; }
    public string PrimaryUri { get; set; }
    public string fileExtension { get; set; }

    public string FileNameWithoutExt
    {
        get
        {
            return Path.GetFileNameWithoutExtension(ActualFileName);
        }
    }

    public string FileNameExtensionOnly
    {
        get
        {
            return System.IO.Path.GetExtension(ActualFileName).Substring(1);
        }
    }

How do I combine these 2 so that i can upload an image for the student to be stored in a blob while returning the URI to the student class?



Solution 1:[1]

Firstly,you need to create azure storage account and container under it from azure portal.Then you can create method like below.You can save the file under a folder under unique file name in azure blob storage and store the file name in your SQL database.The saved file can be accessed via passing the target folder information and unique filename.

Updload File:

    public static void UploadBlob(string targetfolder, string fileName, FileStream fileStream)
    {
        try
        {
            if (!string.IsNullOrWhiteSpace(fileName) && fileStream != null)
            {
                string storageConnection = CloudConfigurationManager.GetSetting("your storage connection string");
                CloudStorageAccount StorageAccount = CloudStorageAccount.Parse(storageConnection);
                CloudBlobClient BlobClient = StorageAccount.CreateCloudBlobClient();
                CloudBlobContainer cloudBlobContainer = BlobClient.GetContainerReference("your container name");

                CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference(targetFolder + fileName);

                blockBlob.UploadFromStream(fileStream);
            }
        }
        catch (Exception ex)
        {
            throw new Exception("File Upload Failed");
        }
    }

Download File:

    public ActionResult DownloadFile()
        {

            Stream stream =DownloadFilelob(targetFolder,fileName)
            return File(stream, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }


public Stream DownloadFileBlob(string targetFolder, string fileName)
{
    try
    {
        if (!string.IsNullOrWhiteSpace(fileName))
        {
            string storageConnection = CloudConfigurationManager.GetSetting("your storage connection string");
            CloudStorageAccount StorageAccount = CloudStorageAccount.Parse(storageConnection);
            CloudBlobClient BlobClient = StorageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer = BlobClient.GetContainerReference("your container name");

            CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference(targetFolder + fileName);

    return blockBlob.OpenRead()
        }
    }
    catch (Exception ex)
    {
        throw new Exception("File Download Failed");
    }
}

Solution 2:[2]

As per the latest way to do this:

public static async Task<bool> UploadFileToStorage(Stream fileStream, string fileName, AzureStorageConfig _storageConfig)
    {
        // Create a URI to the blob
        Uri blobUri = new Uri("https://" +
                              _storageConfig.AccountName +
                              ".blob.core.windows.net/" +
                              _storageConfig.ImageContainer +
                              "/" + fileName);

        // Create StorageSharedKeyCredentials object by reading
        // the values from the configuration (appsettings.json)
        StorageSharedKeyCredential storageCredentials =
            new StorageSharedKeyCredential(_storageConfig.AccountName, _storageConfig.AccountKey);

        // Create the blob client.
        BlobClient blobClient = new BlobClient(blobUri, storageCredentials);

        // Upload the file
        await blobClient.UploadAsync(fileStream);

        return await Task.FromResult(true);
    }

You would need to download the nuget package: Azure.Storage.Blobs version 12.X

Solution 3:[3]

Using Azure CosmosDB for the storage could help. With CosmosDB, you can easily store the image as an attachment to the student document: https://docs.microsoft.com/en-us/rest/api/cosmos-db/attachments

If you don't plan to use CosmosDB, be more precise please about the database storage.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 suhail
Solution 2 Manal Goyal
Solution 3 CEDRIC DERUE