How to Upload Image to Azure Blob using Javascript

Shubhamgautam
4 min readJun 12, 2020

--

So, Let’s begin.

Motive: I want to Upload Image in Azure Blob using Javascript and will see implementation in React js also.

Here, I want to keep this simple as possible so everyone can understand and relate this and apply it to your current project.

So, I’ll keep this step-wise.

Get the Azure Account Storage account with CORS rules set

once it's done….

get the Azure SDK file form this URL from this URL (Javascript v10 SDK for browser )

https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-javascript-client-libraries-legacy

After Downloading you will have 3 Files

Implement the HTML page

Step 1 : Set up the web application:

<!DOCTYPE html>
<html>
<body>
<button id=”create-container-button”>Create container</button>
<button id=”delete-container-button”>Delete container</button>
<button id=”select-button”>Select and upload files</button>
<input type=”file” id=”file-input” multiple style=”display: none;” />
<button id=”list-button”>List files</button>
<button id=”delete-button”>Delete selected files</button>
<p><b>Status:</b></p>
<p id=”status” style=”height:160px; width: 593px; overflow: scroll;” />
<p><b>Files:</b></p>
<select id=”file-list” multiple style=”height:222px; width: 593px; overflow: scroll;” />
</body>
<! — You’ll add code here later in this quickstart. →</html>

Step 2: Add the blob storage client library to the HTML script file

<script src=”azure-storage-blob.js” charset=”utf-8"></script>
<script>
// You’ll add code here in the following sections.
</script>

now the next step…

Step 3: Add the initial JavaScript code

Next, paste the following code into the <script> an element is shown in the previous code block, replacing the placeholder comment.

const createContainerButton = document.getElementById(“create-container-button”);
const deleteContainerButton = document.getElementById(“delete-container-button”);
const selectButton = document.getElementById(“select-button”);
const fileInput = document.getElementById(“file-input”);
const listButton = document.getElementById(“list-button”);
const deleteButton = document.getElementById(“delete-button”);
const status = document.getElementById(“status”);
const fileList = document.getElementById(“file-list”);
const reportStatus = message => {
status.innerHTML += `${message}<br/>`;
status.scrollTop = status.scrollHeight;
}

Add your storage account info:

const accountName = “<Add your storage account name>”;
const sasString = “<Add the SAS you generated earlier>”;
const containerName = “testcontainer”;
const containerURL = new azblob.ContainerURL(
`https://${accountName}.blob.core.windows.net/${containerName}?${sasString}`,
azblob.StorageURL.newPipeline(new azblob.AnonymousCredential));

Create and delete a storage container:

Next, add code to create and delete the storage container when you press the corresponding button.

const createContainer = async () => {
try {
reportStatus(`Creating container “${containerName}”…`);
await containerURL.create(azblob.Aborter.none);
reportStatus(`Done.`);
} catch (error) {
reportStatus(error.body.message);
}
};
const deleteContainer = async () => {
try {
reportStatus(`Deleting container “${containerName}”…`);
await containerURL.delete(azblob.Aborter.none);
reportStatus(`Done.`);
} catch (error) {
reportStatus(error.body.message);
}
};
createContainerButton.addEventListener(“click”, createContainer);
deleteContainerButton.addEventListener(“click”, deleteContainer);

This code calls the ContainerURL to create and delete functions without using an Aborter instance. To keep things simple for this quickstart, this code assumes that your storage account has been created and is enabled. In production code, use an Aborter instance to add timeout functionality.

List blobs:

Next, add code to list the contents of the storage container when you press the List files button.

const listFiles = async () => {
fileList.size = 0;
fileList.innerHTML = “”;
try {
reportStatus(“Retrieving file list…”);
let marker = undefined;
do {
const listBlobsResponse = await containerURL.listBlobFlatSegment(
azblob.Aborter.none, marker);
marker = listBlobsResponse.nextMarker;
const items = listBlobsResponse.segment.blobItems;
for (const blob of items) {
fileList.size += 1;
fileList.innerHTML += `<option>${blob.name}</option>`;
}
} while (marker);
if (fileList.size > 0) {
reportStatus(“Done.”);
} else {
reportStatus(“The container does not contain any files.”);
}
} catch (error) {
reportStatus(error.body.message);
}
};
listButton.addEventListener(“click”, listFiles);

Upload Files:

const uploadFiles = async () => {
try {
reportStatus(“Uploading files…”);
const promises = [];
for (const file of fileInput.files) {
console.log(‘file url’,`https://${accountName}.blob.core.windows.net/${containerName}/${file.name}${sasString}`)
console.log(‘file’,file)
const blockBlobURL = azblob.BlockBlobURL.fromContainerURL(
containerURL,
file.name
);
promises.push(
azblob.uploadBrowserDataToBlockBlob(
azblob.Aborter.none,
file,
blockBlobURL
)
);
}
await Promise.all(promises);
reportStatus(res=>{
console.log(‘res’,res)
})
reportStatus(“Done.”);
listFiles();
} catch (error) {
reportStatus(error.body.message);
}
};
selectButton.addEventListener(“click”, () => fileInput.click());
fileInput.addEventListener(“change”, uploadFiles);

Now, this is all methods that do different -different tasks.

Now you have all the required Methods… Now, its time to put, and let's work for real.

Now, I am implementing all this react js.

now this all Images steps:

Implementation of Azure blob in react js using pure javascript.

Here, we have the entire workflow — — how we upload an image and deploy it to Azure Blob container. It’s pretty simple right.

You can follow this document get started with Azure Blob Storage for Javascript.

See you in the next Post.

--

--