0

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?

  • 2
    Please edit your question and include what you have tried so far and what are the issues you're running into. – Gaurav Mantri Mar 10 '20 at 12:04
  • i'd suggest looking at [this related question](https://stackoverflow.com/q/56793880/272109) (and answers) to get some ideas. As for how to upload your content? That's really up to you - there's no single way to do so. But... after uploading whatever you need to store as a blob, capture the URI of that blob into a property (or *set* of properties) in your document schema. – David Makogon Mar 10 '20 at 18:33

3 Answers3

0

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");
    }
}
suhail
  • 360
  • 1
  • 5
  • 15
0

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

Manal Goyal
  • 29
  • 1
  • 8
-1

Using Azure CosmosDB for the storage could help. With CosmosDB, you can easily store the image as an attachment to the student document: https://learn.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.

  • I wouldn't suggest Cosmos DB attachments as a recommended solution. Aside from requiring all access to go through Cosmos DB itself (vs a direct link to Azure storage, for example), there is a 2GB capacity limit. – David Makogon Mar 10 '20 at 18:30
  • You are right. By the way, 2GB for storing all the photos can be sufficient if you have a moderate number of students and by fixing a size limit for each photo uploaded, – CEDRIC DERUE Mar 11 '20 at 06:50
  • Do NOT use attachments for storing blobs in Cosmos DB. Store your blob in Azure Blob Storage and store the URI for the resource in Cosmos DB. – Mark Brown Mar 11 '20 at 13:24
  • Thank you, Mark, for this discussion. Very exciting. My first answer is not well formulated or I'm wrong. When I'm talking about using an attachment, I suggest storing the reference to the URI for the resource in Azure Storage as an attachment in Cosmos DB. Is this aligned with the documentation on Azure Cosmos DB? – CEDRIC DERUE Mar 12 '20 at 17:24
  • Yes, the correct design is to store the metadata for the blob, including it's URI in Cosmos DB. Thanks. – Mark Brown Mar 14 '20 at 14:59