【问题标题】:How to return the url of an image after uploading it to azure blob storage?将图像上传到 azure blob 存储后如何返回图像的 url?
【发布时间】:2020-11-12 11:34:53
【问题描述】:

我是使用 azure blob sotorage 的新手,我希望在将图像保存到 azure blob 存储后返回其存储 url。

我的代码示例:

  const uploadImage = catchAsync(async (req, res) => {
  const blobName = getBlobName(req.file.originalname);
  const stream = getStream(req.file.buffer);
  const containerClient = blobServiceClient.getContainerClient(containerName);
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  try {
    await blockBlobClient.uploadStream(stream,
      uploadOptions.bufferSize, uploadOptions.maxBuffers,
      { blobHTTPHeaders: { blobContentType: "image/jpeg" } });
      res.send(httpStatus.OK, { message: 'File uploaded to Azure Blob storage.' });
    } catch (err) {
      throw new ApiError(httpStatus.NOT_FOUND, { message: err.message });
    }
});

【问题讨论】:

    标签: node.js azure-blob-storage


    【解决方案1】:

    其实很简单。 BlockBlobClient 有一个名为 url 的属性,它是 blob 的 URL。你可以简单地返回它。

    类似于下面的代码(虽然未经测试):

      const uploadImage = catchAsync(async (req, res) => {
      const blobName = getBlobName(req.file.originalname);
      const stream = getStream(req.file.buffer);
      const containerClient = blobServiceClient.getContainerClient(containerName);
      const blockBlobClient = containerClient.getBlockBlobClient(blobName);
    
      try {
        await blockBlobClient.uploadStream(stream,
          uploadOptions.bufferSize, uploadOptions.maxBuffers,
          { blobHTTPHeaders: { blobContentType: "image/jpeg" } });
          res.send(httpStatus.OK, { blobUrl: blockBlobClient.url, message: 'File uploaded to Azure Blob storage.' });
        } catch (err) {
          throw new ApiError(httpStatus.NOT_FOUND, { message: err.message });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2021-01-16
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多