使用Node.js将Azure Storage blob容器文件复制到Azure File Shares
前置依赖
你需要额外安装Azure File Shares的Node.js SDK,配合原有的Blob SDK使用:
npm install @azure/storage-blob @azure/storage-file-share
实现逻辑
Azure File Share的文件客户端原生支持从URL直接复制内容,无需把Blob内容下载到本地再上传,直接走Azure存储服务端内部链路完成复制,效率极高。同存储账号下使用共享密钥认证时,无需额外生成SAS令牌即可直接调用。
完整示例代码
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob"); const { ShareServiceClient } = require("@azure/storage-file-share"); async function copyBlobToFileShare() { const account = "<你的存储账号名称>"; const accountKey = "<你的存储账号密钥>"; const credential = new StorageSharedKeyCredential(account, accountKey); // 初始化源端Blob服务客户端 const blobServiceClient = new BlobServiceClient( `https://${account}.blob.core.windows.net`, credential ); // 获取源Blob客户端 const sourceContainer = blobServiceClient.getContainerClient("documents"); const sourceBlob = sourceContainer.getBlobClient("file1.png"); // 初始化目标端File Share服务客户端 const shareServiceClient = new ShareServiceClient( `https://${account}.file.core.windows.net`, credential ); // 替换为你的目标文件共享名称、目标目录名称 const shareClient = shareServiceClient.getShareClient("你的目标文件共享名"); // 如果目标共享不存在可以先创建 // await shareClient.createIfNotExists(); const directoryClient = shareClient.getDirectoryClient("目标目录名"); // 如果目标目录不存在可以先创建 // await directoryClient.createIfNotExists(); // 初始化目标文件客户端 const destFileClient = directoryClient.getFileClient(sourceBlob.name); // 调用复制接口,等待复制完成 const copyPoller = await destFileClient.beginCopyFromURL(sourceBlob.url); const copyResult = await copyPoller.pollUntilDone(); console.log("复制状态码:", copyResult._response.status); console.log("复制结果:", copyResult.copyStatus); } copyBlobToFileShare();
注意事项
- 同存储账号下的Blob到File Share复制不产生公网流量,仅收取文件存储的对应费用
- 跨存储账号复制时,需要为源Blob生成带有读权限的SAS令牌,拼接在
sourceBlob.url后再传入复制接口 - 单个文件最大支持复制的大小与Azure File Share的性能层匹配,标准层最大支持4TiB单文件复制
内容的提问来源于stack exchange,提问作者Selyst
相关产品推荐
相关产品推荐

