Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Last active June 2, 2020 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/838ac075236921cdc3fb9eb9419f6c4c to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/838ac075236921cdc3fb9eb9419f6c4c to your computer and use it in GitHub Desktop.
File Upload Controller in .NET Core Web MVC application
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