.net Core File Uploader to Azure Storage
This is the second of a new series of posts on ASP .NET Cadre. In the by week, I had the opportunity to participate in a hackfest with several colleagues from across the globe, to piece of work on real-life customer projects. I took a break from my primary projection to assistance a colleague with a unproblematic trouble: upload a file from a spider web browser and relieve it into Azure Blob Storage within an ASP .NET Core web awarding!
Before y'all begin
Before y'all begin, make sure yous sign in to Azure, create a storage business relationship and make a note of the storage connection information.
Refer to:
- Create a Storage Account: https://docs.microsoft.com/en-us/azure/storage/mutual/storage-quickstart-create-business relationship
- Storage Accounts with .NET: https://docs.microsoft.com/en-united states/azure/storage/blobs/storage-quickstart-blobs-dotnet
"Show me the code!"
Fortunately, I packaged everything nicely as a simple web app project, uploaded into Github and added instructions on how yous tin can use it right away.
Get it here: https://github.com/shahedc/SimpleUpload
I tested information technology in Visual Studio 2017 v15.viii.six and Visual Studio Code, and so either should work for you.
What does it exercise?
To summarize what the lawmaking does, here's a stride-past-step explanation:
- Upload a file submitted in a spider web browser via HTTP Postal service.
- *Catechumen the file to a byte array.
- Save the file data to Azure Blob Storage.
To practise all of the above, I referred to a YouTube video, various blog posts and the official Microsoft docs. I have included the list of references in the Readme page of the Github project.
* NOTE: After I published this web log post, I got some helpful feedback from a couple of readers via Twitter, so I updated the lawmaking with some suggested improvements.
Feedback from oferns: "I left you a comment. You don't need to catechumen to a byte array. You tin can pass the upload stream directly to the client using UploadFromStreamAsync"
I left you a comment. Yous don't need to convert to a byte assortment. You can pass the upload stream direct to the client using UploadFromStreamAsync
— oferns (@oferns) October fourteen, 2018
Feedback from AntonGoretsky: "Temp assortment tin cause LOH fragmentation"
Temp array can cause LOH fragmentation
— Anton Goretsky (@AntonGoretsky) October 14, 2018
In response to the above feedback, I've added a second option to employ the Stream from the FormFile information directly, without converting to a byte array first. This allows me to use CloudBlockBlob.UploadFromStreamAsync() instead of UploadFromByteArrayAsync().
Ok, but what does it REALLY exercise?
Let's have a deeper look at the code.
1. The Alphabetize view under the Abode controller displays one input field for selecting files for upload, and a submit button to complete the upload process.
Hither'southward a snippet:
<form enctype="multipart/form-data" method="postal service"> ... <input multiple="multiple" proper name="files" blazon="file" /> ... <input type="submit" value="Upload" /> ... </class>
2. Next, the Post method of the Home controller handles the uploaded file. It's set up to loop through multiple uploaded files, and upload each file separately. Updated from the original blog post, there are now 2 options.
- Option A: catechumen to byte array before upload
- Choice B: read directly from stream for hulk upload
The UploadToBlob() method still takes in the filename. But now, it can have either have in the byte array or the stream of data from the uploaded file. If one of them is set to null, the other will be used. If both are nil, the method will return false.
// Annotation: uncomment either OPTION A or OPTION B to use one arroyo over another // Option A: catechumen to byte assortment before upload //using (var ms = new MemoryStream()) //{ // formFile.CopyTo(ms); // var fileBytes = ms.ToArray(); // uploadSuccess = await UploadToBlob(formFile.FileName, fileBytes, null); //} // Option B: read direct from stream for blob upload using (var stream = formFile.OpenReadStream()) { uploadSuccess = await UploadToBlob(formFile.FileName, null, stream); }
Yous could change the lawmaking to upload them all to the aforementioned container, but that is upwardly to you.
three. Finally, the UploadToBlob() method in the Home controller uploads the epitome data to a storage container in three stages: create a CloudBlobClient object to represent the storage business relationship, create a container inside that storage account and sets its permissions, upload the paradigm data.
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); ... cloudBlobContainer = cloudBlobClient.GetContainerReference("uploadblob" + Guid.NewGuid().ToString()); look cloudBlobContainer.CreateAsync(); ... BlobContainerPermissions permissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Hulk }; await cloudBlobContainer.SetPermissionsAsync(permissions); ... CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(filename); if (imageBuffer != zip) { // OPTION A: employ imageBuffer (converted from retentiveness stream) wait cloudBlockBlob.UploadFromByteArrayAsync(imageBuffer, 0, imageBuffer.Length); } else if (stream != null) { // Option B: pass in retentiveness stream directly await cloudBlockBlob.UploadFromStreamAsync(stream); } else { return faux; } return truthful;
For obvious security reasons, the connection string for the storage connection is kept in a config file that is not included in the Github repo. Instead there is a placeholder config file that tin can be renamed and updated to refer to any storage account that you ain.
From the Readme file, the instructions are:
- Rename placeholder config file "appsettings.Development.txt" to "appsettings.Evolution.json"
- Supplant placeholder string "<REPLACE_CONN_STRING>" with your Azure Storage Account connection string.
Check your work
Check your Azure account via the portal to ensure that the designated containers have the file(s) yous uploaded.
References
As mentioned in the Readme file, here are the references I used to put together the higher up sample.
- ASP .NET Core File Upload with Form Post: https://www.youtube.com/lookout man?v=dZFucw0Vq9w
- Convert file to byte assortment: https://stackoverflow.com/questions/36432028/how-to-convert-a-file-into-byte-array-directly-without-its-pathwithout-saving-f
- How to access config from Controller: https://blogs.technet.microsoft.com/dariuszporowski/tip-of-the-week-how-to-access-configuration-from-controller-in-asp-internet-core-ii-0/
- Docs article on using .Net to create a hulk in object storage: https://docs.microsoft.com/en-u.s./azure/storage/blobs/storage-quickstart-blobs-dotnet?tabs=windows
- Github repo for hulk access with .NET : https://github.com/Azure-Samples/storage-blobs-dotnet-quickstart
- Using Azure Storage in ASP .NET Cadre: https://wildermuth.com/2017/x/xix/Using-Azure-Storage-in-ASP-Cyberspace-Cadre
- Docs on UploadFromByteArrayAsync: https://docs.microsoft.com/en-united states of america/dotnet/api/microsoft.windowsazure.storage.hulk.cloudblockblob.uploadfrombytearrayasync?view=azure-dotnet
- Docs on UploadFromStreamAsync: https://docs.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.hulk.cloudblockblob.uploadfromstreamasync?view=azure-dotnet
Source: https://wakeupandcode.com/azure-blob-storage-from-asp-net-core-file-upload/
0 Response to ".net Core File Uploader to Azure Storage"
Post a Comment