node.js - 如何读取 Azure Blob URL?

标签 node.js reactjs azure azure-sql-database azure-blob-storage

我正在 React 和 Express/Azure SQL 数据库中创建博客文章列表。我能够使用 Azure blob 存储来存储与帖子关联的图像。我还能够获取 blob url,并将其存储在我的 SQL 数据库中。但是,当我想直接读取 url 时,它会抛出错误“找不到资源”。在搜索文档和其他 stackoverflow 答案后,我可以推断它与 SAS token 有关。谁能解释一下解决这个问题的更好方法是什么?

https://yourdomain.blob.core.windows.net/imagecontainer/yourimage.png

下面是nodejs代码。

router.post('/image', async function (req, res) {
try {
    console.log(req.files.files.data);
    const blobName = 'test' + uuidv1() + '.png';
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blockBlobClient = containerClient.getBlockBlobClient(blobName);
    const uploadBlobResponse = await blockBlobClient.upload(req.files.files.data, req.files.files.data.length)
    res.send({tempUrl:blockBlobClient.url}); 

    } catch (e) {
      console.log(e);
    }
})

最佳答案

However when I want to read the url directly it threw an error resource not found.

您很可能会收到此错误,因为包含 Blob 的 Blob 容器具有 Private ACL,并且匿名访问被禁用。要启用匿名访问,请将 Blob 容器的 ACL 更改为 BlobPublic,这将解决此问题。

如果您无法(或不想)更改 Blob 容器的 ACL,则其他选项是在 Blob 上创建共享访问签名 (SAS)。 SAS 实质上提供了对 blob 的时间和权限限制的访问。根据您的需求,您需要创建一个仅具有读取权限的短期 SAS token 。

要生成 SAS token ,您需要使用 generateBlobSASQueryParameters 方法。创建 SAS token 后,您需要将其附加到 Blob 的 URL 以获取 SAS URL。

这是执行此操作的示例代码。它利用@azure/storage-blob Node 包。

const permissions = new BlobSASPermissions();
permissions.read = true;//Set read permission only.
const currentDateTime = new Date();
const expiryDateTime = new Date(currentDateTime.setMinutes(currentDateTime.getMinutes()+5));//Expire the SAS token in 5 minutes.
var blobSasModel = {
    containerName: 'your-blob-container-name',
    blobName: 'your-blob-name',
    permissions: permissions,
    expiresOn: expiryDateTime
};

const sharedKeyCredential = new StorageSharedKeyCredential('your-storage-account-name', 'your-storage-account-key');
const sasToken = generateBlobSASQueryParameters(blobSasModel, sharedKeyCredential);
const sasUrl = blockBlobClient + "?" + sasToken;//return this SAS URL to the client.

关于node.js - 如何读取 Azure Blob URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68249453/

相关文章:

node.js - View中的node.js express.js错误处理

reactjs - 如何在 React 中使用 <select><option value={true}>?

javascript - 购物车/将多个项目添加到购物车

node.js - 通过node.js在另一个目录中运行npm install

php - 在 Web 服务器上运行带有参数的 python 脚本的最简单方法

javascript - 优化的合并排序比快速排序更快

javascript - 如何在 useState 中使用函数

python - Azure Web作业导入错误: No module named email_validator

amazon-web-services - 为什么我无法在 Azure VNET 中选择子网可用区域以确保高可用性?

c# - 在 Azure Function 中处理从查询到 Azure IOT Hub 的 JSON 响应