【问题标题】:JavaScript Azure Blob Storage move blobJavaScript Azure Blob 存储移动 blob
【发布时间】:2021-10-08 18:22:00
【问题描述】:

我有一个 NodeJS 后端,它使用 Microsoft 的官方 blob 存储库 (@azure/storage-blob) 来管理我的 Blob 存储:

https://www.npmjs.com/package/@azure/storage-blob

必须将 blob 从一个文件夹移动到另一个文件夹。 不幸的是,我找不到任何文档。

到目前为止我所做的是:

const { BlobServiceClient } = require("@azure/storage-blob");

const blobServiceClient = BlobServiceClient.fromConnectionString(process.env.storageconnection);
const containerClient = blobServiceClient.getContainerClient('import');
const blobClient = containerClient.getBlobClient('toImport/' + req.body.file);
const downloadBlockBlobResponse = await blobClient.download();
... do some stuff with the value of the files

就像您在代码中看到的那样,我从文件夹“toImport”中读取了一个文件。之后,我想将文件移动到另一个文件夹“完成”。那可能吗?也许我需要创建文件的副本并删除旧的?

【问题讨论】:

  • Maybe I need to create a copy of the file and delete the old one? - 这正是您需要做的。您无需下载和上传。
  • 但我该怎么做。我找不到那个命令。 getBlobClient() 有什么方法吗?

标签: javascript node.js azure azure-blob-storage


【解决方案1】:

因此,Azure Blob 存储不支持此类移动​​操作。您要做的就是将 blob 从源复制到目标,监控复制进度(因为复制操作是异步的)并在复制完成后删除 blob。

对于复制,您要使用的方法是beginCopyFromURL(string, BlobBeginCopyFromURLOptions)

请看这段代码:

const { BlobServiceClient } = require("@azure/storage-blob");

const connectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key;EndpointSuffix=core.windows.net";
const container = "container-name";
const sourceFolder = "source";
const targetFolder = "target";
const blobName = "blob.png";

async function moveBlob() {
  const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
  const containerClient = blobServiceClient.getContainerClient(container);
  const sourceBlobClient = containerClient.getBlobClient(`${sourceFolder}/${blobName}`);
  const targetBlobClient = containerClient.getBlobClient(`${targetFolder}/${blobName}`);
  console.log('Copying source blob to target blob...');
  const copyResult = await targetBlobClient.beginCopyFromURL(sourceBlobClient.url);
  console.log('Blob copy operation started successfully...');
  console.log(copyResult);
  do {
    console.log('Checking copy status...')
    const blobCopiedSuccessfully = await checkIfBlobCopiedSuccessfully(targetBlobClient);
    if (blobCopiedSuccessfully) {
      break;
    }
  } while (true);
  console.log('Now deleting source blob...');
  await sourceBlobClient.delete();
  console.log('Source blob deleted successfully....');
  console.log('Move operation complete.');
}

async function checkIfBlobCopiedSuccessfully(targetBlobClient) {
  const blobPropertiesResult = await targetBlobClient.getProperties();
  const copyStatus = blobPropertiesResult.copyStatus;
  return copyStatus === 'success';
}

moveBlob();

【讨论】:

  • 太棒了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-03-02
  • 2016-03-04
  • 2017-11-10
  • 2019-08-17
  • 2017-04-18
  • 2017-08-18
  • 2014-01-13
  • 1970-01-01
相关资源
最近更新 更多