asp.net-mvcazureazure-cosmosdbazure-blob-storagedocument-database

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:

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

  • 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");
            }
        }