First published on MSDN on Oct 25, 2018
Many web application needs end-users to upload files for processing. And these files need to be stored in a persisted storage. One common practice is, developers write code to upload the file and save it on the webserver itself. This approach is OK if the file size is small and/or smaller number of uploads. Recommended approach is, let the browse upload the files to Azure Storage directly without need to talk to webserver. This option, frees up webserver for other business processing.
For browser to talk to Azure Storage, instead of exposing storage connection string, we can use SAS Key (Share Access Security). SAS key is valid only for limited time and has specific permissions like write but not read or list. For more details on SAS keys please see
here
Here is quick sample to upload blob files to Azure Storage from a browser directly and then process it the server side.
Blob files are uploaded directly from browser to Storage using SAS Key
Browser sends the blob file name to Web server
Web server access blob using connection string
1. Download JavaScript Client library for Azure Storage
Download the zip from
https://aka.ms/downloadazurestoragejs
More details on this client library is found
here
and
here
2. Generate SAS token
Log into Azure portal
https://portal.Azure.com
Navigate to your Storage Account
Click on the
Share Access Signature
Select write only as shown below and click Generate SAS token button
Copy SAS token
Note : you may have to change expiry date/time if you are planning to use this SAS key for longer duration
3. Enable CORS
Log into Azure Portal
https://portal.azure.com
Navigate to your Azure Storage account
Click on CORS
Set these following values and hit Save button
4. Client side code
Extract the above zip file and copy the
azure-storage.blob.min.js
to your application scripts folder. For ASP.NET MVC application, you can copy it to
Script
folder as shown below
In your client side code, add these lines
[code language=”javascript”]
<br/>//this Azure Storage JavaScript Client Library<br/>
Select file to upload to blob
Upload to blob
Do server side processing
<br/><br/> var blobname;<br/> function blobUpload() {<br/> // blob client<br/> var blobUri = ‘https://STORAGENAME.blob.core.windows.net’;<br/> var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, ‘SASKEY’);<br/><br/> // blob upload<br/> var file = document.getElementById(‘blobFile’).files[0];<br/><br/> var customBlockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 * 512;<br/> blobService.singleBlobPutThresholdInBytes = customBlockSize;<br/><br/> var filename = file.name.substring(0, file.name.lastIndexOf(‘.’));<br/> var ext = file.name.substring(file.name.lastIndexOf(‘.’));<br/><br/> blobname = filename + ‘_’ + Math.random().toString(16).slice(2) + ext;<br/><br/> var speedSummary = blobService.createBlockBlobFromBrowserFile(‘CONTAINER’, blobname, file, { blockSize: customBlockSize }, function (error, result, response) {<br/> if (error) {<br/> // Upload blob failed<br/> alert(“blob upload failed : check CORS”);<br/> } else {<br/> // Upload successfully<br/> alert(“blob upload successfull”);<br/> }<br/> });<br/><br/> var bcheckList = false;<br/> if (bcheckList) {<br/> // blob list<br/> blobService.listBlobsSegmented(‘CONTAINER’, null, function (error, results) {<br/> if (error) {<br/> // List blobs error<br/> alert(“blob list failed : check SAS token”);<br/> } else {<br/> for (var i = 0, blob; blob = results.entries[i]; i++) {<br/> // blob object<br/> alert(“blob found : ” + blob);<br/> }<br/> }<br/> });<br/> }<br/> }<br/><br/> function serverside() {<br/> var newURL = location.protocol + “//” + location.host + “/Home/Contact?id=” + blobname;<br/> newURL = encodeURI(newURL)<br/> //alert(newURL);<br/> window.location = newURL;<br/> }<br/><br/>
[/code]
5. Server side code
Add following code on your server side
[code language=”csharp”]
public ActionResult Contact(string id)
{
// id is blob file name
CloudStorageAccount storageAccount = null;
CloudBlobContainer cloudBlobContainer = null;
var storageConnectionString = “CONNECTION STRING TO STORAGE”;
CloudStorageAccount.TryParse(storageConnectionString, out storageAccount);
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
cloudBlobContainer = cloudBlobClient.GetContainerReference(“CONTAINER”);
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(id);
ViewBag.Message = “Your contact page.”;
return View();
}
[/code]