Azure Blob Storage - File upload using Azure Serverless Functions in Node.JS
How to Upload Files to Azure Blob Storage Using Azure Serverless Functions in Node.js
In the world of cloud computing, Azure Blob Storage is a highly scalable object storage solution that allows you to store large amounts of unstructured data. When combined with Azure Functions, a serverless compute service, you can create powerful applications without worrying about server management. In this blog post, we will walk through how to upload files to Azure Blob Storage using Azure Functions written in Node.js.
Prerequisites
Before we get started, make sure you have the following:
- Azure Account: You need an active Azure subscription. If you don't have one, you can create a free account here.
- Node.js: Ensure that you have Node.js installed on your machine. You can download it from nodejs.org.
- Azure Storage Account: Create a storage account in Azure. Follow the official documentation if you need guidance.
Setting Up Your Azure Function
Step 1: Create a New Azure Function Project
Open your terminal or command prompt.
Create a new directory for your project and navigate into it:
mkdir AzureBlobUploadFunction cd AzureBlobUploadFunctionInitialize a new Azure Functions project:
func init --javascript
Step 2: Create a New Function
Now, let's create a new HTTP-triggered function that will handle the file upload.
Run the following command:
func new --name UploadFile --template "HTTP trigger"Navigate to the newly created function folder:
cd UploadFile
Step 3: Install Required Packages
To interact with Azure Blob Storage, you will need the Azure Storage Blob client library. Install it using npm:
npm install @azure/storage-blob
Step 4: Configure Your Function
Now, let’s update the index.js file in the UploadFile folder to handle file uploads.
const { BlobServiceClient } = require('@azure/storage-blob');
module.exports = async function (context, req) {
if (req.method !== 'POST') {
context.res = {
status: 405,
body: "Method not allowed"
};
return;
}
const connectionString = process.env.AzureWebJobsStorage; // Use connection string from environment variable
const containerName = 'uploads'; // Name of your blob container
// Create BlobServiceClient
const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
const containerClient = blobServiceClient.getContainerClient(containerName);
try {
// Ensure the container exists
await containerClient.createIfNotExists();
// Generate a unique name for the file
const blobName = req.body.fileName; // Expect fileName in the request body
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
// Upload the file
const uploadBlobResponse = await blockBlobClient.upload(req.body.fileData, Buffer.byteLength(req.body.fileData));
context.res = {
status: 200,
body: `Upload successful. Blob URL: ${blockBlobClient.url}`
};
} catch (error) {
context.res = {
status: 500,
body: `Error uploading file: ${error.message}`
};
}
};
Step 5: Configure Environment Variables
Set the AzureWebJobsStorage environment variable to your Azure Storage account connection string. You can find this in the Azure portal under your Storage Account settings.
To set it locally, create a file named local.settings.json in the root of your project and add the following:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "<Your_Connection_String>",
"FUNCTIONS_WORKER_RUNTIME": "node"
}
}
Step 6: Run Your Function Locally
You can run your function locally to test it:
func start
Step 7: Testing the Upload
To test the file upload, you can use tools like Postman or curl. For example, if you’re using Postman, configure it as follows:
- Method: POST
- URL:
http://localhost:7071/api/UploadFile - Body: Choose "raw" and set the type to JSON. Use the following structure:
{ "fileName": "example.txt", "fileData": "Hello, World!" }
Step 8: Deploying to Azure
Once you’re satisfied with your local testing, deploy your function to Azure:
Run the following command:
func azure functionapp publish <Your_Function_App_Name>After deployment is complete, you can use the function URL provided by Azure to upload files.
Conclusion
In this tutorial, we walked through the process of uploading files to Azure Blob Storage using Azure Functions in Node.js. We created a function that handles file uploads via HTTP requests and demonstrated how to deploy it to Azure. This serverless architecture allows for scalable and efficient file handling in your applications.
Feel free to explore further and enhance your function with additional features such as authentication, logging, or more complex data handling. Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment