设置大小限制以通过 SAS URL 直接上传到 azure blob 存储

问题描述 投票:0回答:1

我的前端应用程序接收到 SAS URL 以直接上传到 天蓝色的 blob 存储容器。然而,在生成 SAS URL 时,我找不到设置上传大小限制的方法。

这是示例代码

    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
azure upload blob storage
1个回答
0
投票

设置大小限制以通过 SAS URL 直接上传到 azure blob 存储

根据 Sumarigo-MSFT 的 MS 问答

Azure Blob 存储不直接支持直接在共享访问签名 (SAS) 中设置文件大小限制。

相反,您可以通过在创建 SAS 之前在应用程序代码中添加检查来强制执行文件大小限制。

在我的环境中,我创建了前端代码并设置了文件大小限制,如下所示:

代码:

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);
    }
});

在我的环境中,我设置了 5MB 文件大小的限制。

后端脚本:

// 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}`);
});

输出: 如果文件大小超过 5MB,上传前会显示警告。

enter image description here

传送门: enter image description here

如果文件大小低于 5MB,它将上传到 Azure Blob 存储中。

© www.soinside.com 2019 - 2024. All rights reserved.