Last active
June 2, 2020 13:47
-
-
Save manoj-choudhari-git/838ac075236921cdc3fb9eb9419f6c4c to your computer and use it in GitHub Desktop.
File Upload Controller in .NET Core Web MVC application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FileUploadController : Controller | |
{ | |
private readonly StorageConfig storageConfig; | |
public FileUploadController(StorageConfig storageConfig) | |
{ | |
this.storageConfig = storageConfig; | |
} | |
[HttpPost("FileUpload")] | |
public async Task<IActionResult> Index(List<IFormFile> files) | |
{ | |
long size = files.Sum(f => f.Length); | |
string fileNamePattern = @"^[\w\-. ]+$"; | |
var filePaths = new List<string>(); | |
foreach (var formFile in files) | |
{ | |
if (formFile.Length > 0) | |
{ | |
bool shouldProcess = Regex.IsMatch(formFile.FileName, fileNamePattern); | |
if (shouldProcess) | |
{ | |
filePaths.Add(formFile.FileName); | |
await UploadFileToStorage(formFile.OpenReadStream(), formFile.FileName); | |
} | |
} | |
} | |
return Ok(new { message = "Files uploaded to Blob", count = files.Count, size, filePaths }); | |
} | |
private async Task<bool> UploadFileToStorage(Stream fileStream, string fileName) | |
{ | |
//// STEP 1: Create Blob URI | |
string blobHost = $"https://{storageConfig.AccountName}.blob.core.windows.net/"; | |
string containerFilePart = $"{storageConfig.ContainerName}/{fileName}"; | |
Uri blobUri = new Uri($"{blobHost}{containerFilePart}"); | |
// STEP 2: Storage Credentials | |
StorageSharedKeyCredential storageCredentials | |
= new StorageSharedKeyCredential(storageConfig.AccountName, | |
storageConfig.Key); | |
// STEP 3: Upload using BlobClient object | |
BlobClient blobClient = new BlobClient(blobUri, storageCredentials); | |
await blobClient.UploadAsync(fileStream); | |
return await Task.FromResult(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment