npm install @azure/storage-blob\n
npm install uuid dotenv
Last active
June 23, 2023 12:40
-
-
Save frbayart/2c84534a6c52e9b924873c1be1e99fc2 to your computer and use it in GitHub Desktop.
Azure NodeJs upload to storage account
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { BlobServiceClient } = require("@azure/storage-blob"); | |
const { v1: uuidv1 } = require("uuid"); | |
require("dotenv").config(); | |
async function main() { | |
try { | |
console.log("Azure Blob storage v12 - JavaScript quickstart sample"); | |
// Quick start code goes here | |
} catch (err) { | |
console.err(`Error: ${err.message}`); | |
} | |
} | |
main() | |
.then(() => console.log("Done")) | |
.catch((ex) => console.log(ex.message)); | |
const AZURE_STORAGE_CONNECTION_STRING = | |
process.env.AZURE_STORAGE_CONNECTION_STRING; | |
if (!AZURE_STORAGE_CONNECTION_STRING) { | |
throw Error('Azure Storage Connection string not found'); | |
} | |
// // Create the BlobServiceClient object with connection string | |
const blobServiceClient = BlobServiceClient.fromConnectionString( | |
AZURE_STORAGE_CONNECTION_STRING | |
); | |
// Create a unique name for the container | |
// const containerName = 'quickstart' + uuidv1(); | |
const containerName = 'attachment'; | |
console.log('\nCreating container...'); | |
console.log('\t', containerName); | |
// Get a reference to a container | |
const containerClient = blobServiceClient.getContainerClient(containerName); | |
// // // Create a unique name for the blob | |
const blobName = 'testdir/quickstart' + uuidv1() + '.txt'; | |
// Get a block blob client | |
const blockBlobClient = containerClient.getBlockBlobClient(blobName); | |
// // // Display blob name and url | |
console.log( | |
`\nUploading to Azure storage as blob\n\tname: ${blobName}:\n\tURL: ${blockBlobClient.url}` | |
); | |
// // Upload data to the blob | |
const data = 'Hello, World!'; | |
const uploadBlobResponse = blockBlobClient.upload(data, data.length); | |
console.log( | |
`Blob was uploaded successfully. requestId: ${uploadBlobResponse.requestId}` | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment