File Upload
We have used Azure Blob Storage for file upload.
Overview of Blob Storage
Azure Blob Storage is Microsoft's Object Storage Solution for the cloud. Blob Storage is optimized for storing massive amounts of unstructured data. Unstructured data is the data that does not adhere to a data model or definition, such as text or binary data.
To use the Blob Storage, you have to create an account on the
Azure portal.
Navigate to your new Storage Account in the Azure Portal.
- Open Windows Azure account and click "Storage Account" in the left menu bar.
- The selected option will be redirected into Storage Account page and there, you click on "Add".
- Select the subscription in which you want to create the Storage Account.
- Under the Resource Group field, select "Create new". Enter a name for your new resource group, as shown in the following image.
- Next, enter a name for your storage account. The name you choose must be unique across Azure. The name also must be between 3 and 24 characters in length and can include numbers and lowercase letters only.
- Select a location for your storage account or use the default location.
- Select "Review + Create" on the bottom of the screen. Do not select "Create" in the next step.
- Locate your storage account.
- In the Settings section of the storage account overview, select Access keys. Here, you can view your account access keys and the complete connection string for each key.
- Find the connection string value under key1 and select the "Copy" button to copy the connection string. You will add the connection string value to an environment variable in the next step.
- Save storage connection string in the appsettings.json file. Also, add container name for storage.
.NET CODE Implementation
Use the following code implementation on your Visual Studio framework.
- "AzureConnectionStrings": {
- "StorageConnection": "DefaultEndpointsProtocol=https;AccountName=hstorage;AccountKey=1dYm3E5YqDkxZF5MJybdMngkhPaZepzEup7b9vpvW+sTliGn4mwIskRUsYsIpaLJb2LKerOg==;EndpointSuffix=core.windows.net",
- "appcontainer": "h-app"
- },
- Create the folder name dynamically based on the Application Id.
CODE
- #region "Document upload"
-
-
-
-
-
- [HttpPost]
- [Route("fileupload")]
- [RequestFormSizeLimit(valueCountLimit: 29283939, Order = 1)]
- public async Task < IActionResult > UploadDocument(FileUpload fileUpload) {
-
- try {
- if (fileUpload.ApplicationId > 0) {
- var folderStructure = $” Application - {
- fileUpload.ApplicationId
- }
- /ownerInfo";
-
- var uploaded = await this.ApplicationHelper.UploadFile(fileUpload, folderStructure);
- return Ok(uploaded);
- }
- return new JsonResult("Id cannot be null");
- } catch (Exception ex) {
- return BadRequest(new JsonResult(ex.Message));
- }
- }#endregion
- After initialization of container, it will return the blob storage name, URI.
CODE
This method is used to upload a file from .NET development to Azure Storage Account.
-
-
-
-
-
-
- public async Task<FileUploaded> UploadFile(FileUpload Data, string FolderPath)
- {
- CloudBlockBlob blockBlob;
-
- string cFileName = MakeValidFileName(Data.File.FileName);
-
-
- var container = await InitFileUpload();
-
- var dirPath = container.GetDirectoryReference(FolderPath);
- if (dirPath == null)
- {
-
- blockBlob = container.GetBlockBlobReference(cFileName.AppendTimeStamp());
- await blockBlob.UploadFromStreamAsync(Data.File.OpenReadStream());
- }
- else
- {
-
- blockBlob = dirPath.GetBlockBlobReference(cFileName.AppendTimeStamp());
- await blockBlob.UploadFromStreamAsync(Data.File.OpenReadStream());
- }
-
- var extn = FileExtention(blockBlob.Uri.AbsolutePath);
-
- var uploaded = new FileUploaded()
- {
- MimeType = extn,
- OriginalFileName = blockBlob.Name,
- Path = blockBlob.Uri.AbsoluteUri,
- };
-
- var uploadedData = new FileUploaded();
-
- if (uploaded != null)
- {
-
- uploadedData.Id = uploaded.Id;
- uploadedData.FileName = Data.File.FileName;
- uploadedData.OriginalFileName = uploaded.OriginalFileName;
- uploadedData.Path = uploaded.Path;
- uploadedData.Size = Convert.ToInt32(Data.File.Length);
- uploadedData.MimeType = Data.File.ContentType;
- uploadedData.FileType = FileExtention(uploaded.Path);
- uploadedData.Status = true;
- uploadedData.OwnerId = Data.OwnerId;
- uploadedData.ApplicationId = Data.ApplicationId;
-
- }
- return uploadedData;
- }
-
-
-
-
-
-
- public static string MakeValidFileName(string name)
- {
- string invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
- string invalidRegStr = string.Format(@"([{0}]*\.+$ )|([{0}]+)", invalidChars);
- var cname = System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, "_");
- return cname.Replace(" ", "-").ToLower();
- }
-
-
-
-
- public string FileExtention(string path)
- {
- var extn = Path.GetExtension(path);
- return extn.Substring(1, extn.Length - 1);
- }
- Use this Storage Connection String to file upload. (Helper Class)
CODE
This will read and connect a trust to Windows Azure through connection strings.
-
-
-
-
- public async Task < CloudBlobContainer > InitFileUpload() {
-
- string storageConnectionString = _configuration.GetSection("AzureConnectionStrings").GetSection("StorageConnection").Value;
-
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
-
- CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
- string appcontainer = _configuration.GetSection("AzureConnectionStrings").GetSection("appcontainer").Value;
-
- CloudBlobContainer container = blobClient.GetContainerReference(appcontainer);
-
- await container.CreateIfNotExistsAsync();
-
- await container.SetPermissionsAsync(new BlobContainerPermissions {
- PublicAccess = BlobContainerPublicAccessType.Blob
- });
- return container;
- }
- Save the file name, URI in DB.
I hope this helps.