.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!

ASPNETCoreLogo-300x267

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.

Web 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.

simple-upload-ui

What does it exercise?

To summarize what the lawmaking does, here's a stride-past-step explanation:

  1. Upload a file submitted in a spider web browser via HTTP Postal service.
  2. *Catechumen the file to a byte array.
  3. 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"

Feedback from AntonGoretsky: "Temp assortment tin cause LOH fragmentation"

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:

  1. Rename placeholder config file "appsettings.Development.txt" to "appsettings.Evolution.json"
  2. 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.

simple-upload-portal

References

As mentioned in the Readme file, here are the references I used to put together the higher up sample.

  1. ASP .NET Core File Upload with Form Post: https://www.youtube.com/lookout man?v=dZFucw0Vq9w
  2. Convert file to byte assortment: https://stackoverflow.com/questions/36432028/how-to-convert-a-file-into-byte-array-directly-without-its-pathwithout-saving-f
  3. 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/
  4. 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
  5. Github repo for hulk access with .NET : https://github.com/Azure-Samples/storage-blobs-dotnet-quickstart
  6. Using Azure Storage in ASP .NET Cadre: https://wildermuth.com/2017/x/xix/Using-Azure-Storage-in-ASP-Cyberspace-Cadre
  7. Docs on UploadFromByteArrayAsync: https://docs.microsoft.com/en-united states of america/dotnet/api/microsoft.windowsazure.storage.hulk.cloudblockblob.uploadfrombytearrayasync?view=azure-dotnet
  8. Docs on UploadFromStreamAsync: https://docs.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.hulk.cloudblockblob.uploadfromstreamasync?view=azure-dotnet

schulersicals.blogspot.com

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel