azureuploadblobstorage

Set size limt to direct upload to azure blob storage via SAS URL


I have my Frontend Application that received SAS URL to do a direct upload to azure blob storage container. However upon generating SAS URL, I can't find a way to set a size limit to the uploaded.

here is a sample code

    const sasPermissions = new ContainerSASPermissions();
    sasPermissions.write = true; // Allow write permissions
   
    // Generate SAS query parameters
    const sasToken = generateBlobSASQueryParameters({
      containerName,
      blobName,
      protocol: 'https',
      permissions: sasPermissions,
      expiresOn: expiryDate
    }, sharedKeyCredential).toString();

    // Construct SAS URL
    const sasUrl = `${blockBlobClient.url}?${sasToken}`;
    return sasUrl

Solution

  • Set size limt to direct upload to azure blob storage via SAS URL

    According to this MS Q&A by Sumarigo-MSFT.

    Azure Blob Storage doesn't directly support to set a file size limit directly within a Shared Access Signature (SAS).

    Instead, you can enforce a file size limit by adding a check in your application code before you create the SAS.

    In my environment, I created Frontend Code with set the size of file limit Like below:

    Code:

    document.getElementById('uploadButton').addEventListener('click', async () => {
        const fileInput = document.getElementById('fileInput');
        const file = fileInput.files[0];
        const maxSizeInMB = 5; // Maximum file size in megabytes
    
        if (file && file.size > maxSizeInMB * 1024 * 1024) {
            alert(`File size exceeds the limit of ${maxSizeInMB}MB.`);
            return;
        }
    
        try {
            // Request SAS URL from the server
            const response = await fetch(`/generate-sas-url?blobName=${file.name}`);
            const data = await response.json();
            const sasUrl = data.sasUrl;
    
            // Perform the upload using fetch API
            const uploadResponse = await fetch(sasUrl, {
                method: 'PUT',
                headers: {
                    'x-ms-blob-type': 'BlockBlob' // Required for blob uploads
                },
                body: file
            });
    
            if (uploadResponse.ok) {
                console.log(`Upload block blob ${file.name} successfully`);
            } else {
                console.error('Error uploading file:', uploadResponse.statusText);
            }
        } catch (error) {
            console.error('Error uploading file:', error.message);
        }
    });
    

    In my environment, I set an limit of 5MB file size.

    Backend script:

    // server.js
    const express = require('express');
    const { generateBlobSASQueryParameters, ContainerSASPermissions,StorageSharedKeyCredential } = require('@azure/storage-blob');
    
    const app = express();
    const port = 3000;
    
    // Configure your Azure Storage credentials
    const accountName = 'venkat326123';
    const accountKey = 'T3czZpu1gZ0nLKiCuli9a6txxxxx=';
    const sharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);
    const containerName = 'venkat';
    
    app.use(express.static('public')); // Serve static files from 'public' directory
    
    app.get('/generate-sas-url', (req, res) => {
        const blobName = req.query.blobName;
        const expiryDate = new Date(new Date().valueOf() + 3600 * 1000); // 1 hour expiration
    
        const sasPermissions = new ContainerSASPermissions();
        sasPermissions.write = true; // Allow write permissions
    
        const sasToken = generateBlobSASQueryParameters({
            containerName,
            blobName,
            protocol: 'https',
            permissions: sasPermissions,
            expiresOn: expiryDate
        }, sharedKeyCredential).toString();
    
        const sasUrl = `https://${accountName}.blob.core.windows.net/${containerName}/${blobName}?${sasToken}`;
        res.json({ sasUrl });
    });
    
    app.listen(port, () => {
        console.log(`Server running at http://localhost:${port}`);
    });
    

    Output: If the file size is above 5MB it will show warning before uploading.

    enter image description here

    Portal: enter image description here

    If the file size is below 5MB it will upload in Azure Blob Storage.