ABSYZ ABSYZ

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

ABSYZ

Uploading files from Salesforce to Azure Blob Storage

Home / Article & Blogs / Salesforce / Uploading files from Salesforce to Azure Blob Storage
By nagensahu inSalesforce

In recent times, AWS S3 has been the focus for people looking to store large volumes of files. This blog focuses on using Microsoft’s Azure Blob storage to do the same.

In essence, Azure Blob storage has a very similar structure to S3. You need to start with creating a storage account. Inside the account there need to be containers, which is like a bucket in S3. Inside the container is where you will be storing your files. For our purpose we will using a type of blob called Block blob.

Folder structure is logical – exactly like in S3.

Configuring Azure Blob is straightforward:

Screen Shot 2018-02-18 at 5.17.47 PM

You should note down the Storage Key from here:

Screen Shot 2018-02-18 at 5.18.07 PM

We will discuss the Shared Key method of authentication here. Shared Key Authentication to Azure Blob also uses a signature calculation like S3. We need to create a signature string and calculate the hash. There is a version that needs to be specified for calculation of signature. The version decides the format of the signature. Here, we are using the version called ‘2015-12-11’.

Exact details of authentication mechanism here

The timestamp needs to be formatted as below using the formatGMT method in Datetime class:

timestamp.formatGMT('EEE, dd MMM yyyy HH:mm:ss z');

Make sure to URL encode the file name:

fileName = EncodingUtil.urlEncode(fileName, 'UTF-8');

The file length has to be converted to string:

fileLength = String.valueof(fileLength);

This is what the canonicalized headers should look like:

canonicalHeader = 'x-ms-blob-type:BlockBlob\nx-ms-date:'+timestamp+'\nx-ms-version:2015-12-11\n';

This is what the canonicalized resource should look like:

canonRes = '/'+wrapRec.storageName+'/'+containerName+'/'+wrapRec.fileName;

The final string that will need to be signed using HMAC256

stringToSign = 'PUT\n\n\n'+fileLength+'\n\n'+fileType+'\n\n\n\n\n\n\n'+canonHeaders+canonRes;

Sign the request using the combination of storage key and the signature:

Blob temp = EncodingUtil.base64Decode(StorageKey);
Blob hmac = Crypto.generateMac('hmacSHA256', Blob.valueOf(stringToSign), temp);
Blob.valueOf(stringToSign), temp);
signature = EncodingUtil.base64Encode(hmac);

After this, its a matter of creating the HTTP request:
[sourcecode language="java"]

req.setMethod('PUT');
req.setHeader('x-ms-blob-type', 'BlockBlob');
req.setHeader('x-ms-date', timestamp);
string authHeader = 'SharedKey '+storageName+':' + signature;
req.setHeader('Authorization', authHeader);
req.setHeader('x-ms-version', '2015-12-11');
req.setHeader('Content-Length', fileLength);
req.setHeader('Content-Type', fileType);
req.setEndpoint('https://'+storageName+'.blob.core.windows.net/'+container+'/'+fileName);
req.setBodyAsBlob(fileBody);

[/sourcecode]



Make sure that anonymous access is enabled on your container, so that you can access the file from a link. The link to the uploaded file will be something like:

https://’Storage Name’.blob.core.windows.net/’Container name’/’File Name’

Now this was Apex. When uploading a file from the Apex server side, you will always be limited by the Governor limits imposed like the Size of the HTTP request and the Heap size, which means low size of the uploads you can do from Apex.

Although Azure does not have a specific library for javascript, it’s node.js library can be converted to a javascript library for usage on a page. The details are here.

So if you want to do the upload on a html page, you will need to generate a library from the latest node.js build. For our purpose, we need to generate and use 2 js libraries: the Azure common library and the Azure Blob library. Follow the instructions in the link above to generate them.

Once generated, the library can be directly used as static resources. The great thing about the library is that you do not need to explicitly calculate the signed string, all of the steps that we had to do with apex is handled by the library.

When the Azure Common library is loaded, you have an object call AzureStorage available in the script. This object has the functions that will be used to instantiate the Blob service as an object.

AzureStorage.createBlobService(storage.storageName,
storage.storageKey);

After that use related functions to perform your task.

listBlobsSegmented

– returns a list of all the blobs in the storage.

createBlockBlobFromBrowserFile

– Creates a blob from a file on the page.

There are many other functions available. The javascript library has the same functions available as the Azure node.js library.

Sample usage below:

[sourcecode language="java"]

function uploadFile() {
var file = document.getElementById('theFile').files[0];
var customBlockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 * 1024 * 1;
blobService.singleBlobPutThresholdInBytes = customBlockSize;
if (blobService) {
speedSummary = blobService.createBlockBlobFromBrowserFile(
container,
file.name,
file,
{
blockSize: customBlockSize
},
function(error, result, response) {
finishedOrError = true;
if (error) {
document.getElementById("response").innerHTML = JSON.stringify(error);
} else {
alert("uploaded !");
}
});
}
}

[/sourcecode]

The full code for the Apex and Visualforce is here.

AzureBlob StorageFiles
108
Like this post
5 Posts
nagensahu

Search Posts

Archives

Categories

Recent posts

All About The OmniStudio FlexCards

All About The OmniStudio FlexCards

Boost Customer Experience With Repeater Widget in CRM Analytics

Boost Customer Experience With Repeater Widget in CRM Analytics

Enhance Insights Using Custom Tooltips In CRM Analytics

Enhance Insights Using Custom Tooltips In CRM Analytics

Net zero as a Service In CPG Industry

Net zero as a Service In CPG Industry

How Do We Import an External Library into Salesforce Lightning?

How Do We Import an External Library into Salesforce Lightning?

  • Previous PostSalesforce Marketing Cloud vs Pardot
  • Next PostCreate Salesforce Survey (Spring 18 Feature)

Related Posts

All About The OmniStudio FlexCards
OmniStudio Salesforce

All About The OmniStudio FlexCards

Boost Customer Experience With Repeater Widget in CRM Analytics
CRM Analytics Salesforce

Boost Customer Experience With Repeater Widget in CRM Analytics

Enhance Insights Using Custom Tooltips In CRM Analytics
CRM Analytics Salesforce

Enhance Insights Using Custom Tooltips In CRM Analytics

How Do We Import an External Library into Salesforce Lightning?
Lightning Salesforce

How Do We Import an External Library into Salesforce Lightning?

2 Comments

  1. Pankaj
    Reply
    13 May 2022

    Hello, I am trying to upload file on Azure using Apex but facing error as ‘System.HttpResponse[Status=Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature., StatusCode=403]’
    Could you please help me on this?

    Reply
  2. Pankaj
    Reply
    16 May 2022

    hi, I am trying to upload the file to Azure Blob storage using Apex (HTTP call) but facing error as ‘Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature., StatusCode=403’ could you please help me. Thanks

    Reply

Leave a Reply (Cancel reply)

Your email address will not be published. Required fields are marked *

*
*

ABSYZ Logo

INDIA | USA | UAE

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White Papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

youngsoft
Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT