JavaScript Azure Blob 存储移动 blob
Posted
技术标签:
【中文标题】JavaScript Azure Blob 存储移动 blob【英文标题】:JavaScript Azure Blob Storage move 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() 有什么方法吗?
【参考方案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();
【讨论】:
太棒了。非常感谢!以上是关于JavaScript Azure Blob 存储移动 blob的主要内容,如果未能解决你的问题,请参考以下文章
使用 C#(无 JavaScript)直接将 Blazor WebAssembly 文件分块到 Azure Blob 存储
有没有办法通过 Javascript 删除 Azure Blob 容器文件?
基于Azure blob storage T级别HBase表恢复