Azure CLI的upload-batch命令在@azure/storage-blob SDK中是否有对应API?
Azure JavaScript SDK 实现Blob存储文件夹批量上传
@azure/storage-blob包本身并没有提供和Azure CLI中az storage blob upload-batch完全一致的开箱即用API,但可以通过结合Node.js的文件系统模块遍历本地文件夹,再调用SDK的单个Blob上传方法,轻松实现等价的批量上传功能。
实现步骤与代码示例
安装依赖
可以使用原生fs模块,也可以用fs-extra简化文件操作:npm install @azure/storage-blob fs-extra封装批量上传函数
以下代码实现了递归遍历本地文件夹(包含子文件夹),并将所有文件上传到指定Blob存储路径:const { BlobServiceClient } = require("@azure/storage-blob"); const fs = require("fs-extra"); const path = require("path"); async function uploadFolderToBlob(localFolderPath, containerName, destinationPath, connectionString) { // 初始化Blob服务客户端 const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString); const containerClient = blobServiceClient.getContainerClient(containerName); // 遍历本地文件夹内的所有项 const entries = await fs.readdir(localFolderPath, { withFileTypes: true }); for (const entry of entries) { const fullLocalPath = path.join(localFolderPath, entry.name); // 递归处理子文件夹 if (entry.isDirectory()) { const subDestPath = path.join(destinationPath, entry.name); await uploadFolderToBlob(fullLocalPath, containerName, subDestPath, connectionString); continue; } // 构造Blob存储路径(统一使用正斜杠适配Blob格式) const blobPath = path.join(destinationPath, entry.name).replace(/\\/g, "/"); const blockBlobClient = containerClient.getBlockBlobClient(blobPath); // 上传文件 try { await blockBlobClient.uploadFile(fullLocalPath); console.log(`成功上传: ${blobPath}`); } catch (err) { console.error(`上传失败 ${fullLocalPath}:`, err.message); } } } // 使用示例 const storageConnectionString = "<你的Azure存储账户连接字符串>"; const localSourceFolder = "./local-files"; const targetContainerName = "my-storage-container"; const remoteDestPath = "uploaded-folder"; uploadFolderToBlob(localSourceFolder, targetContainerName, remoteDestPath, storageConnectionString) .then(() => console.log("文件夹批量上传完成")) .catch(err => console.error("上传任务失败:", err));
额外说明
- 上述代码的行为和
az storage blob upload-batch一致,会递归处理子文件夹并保持目录结构。 - 对于大文件,可以替换为
uploadStream方法来优化内存占用;如果需要提升上传速度,可以添加并发控制(注意不要超过Azure存储的请求限制)。 - 官方SDK没有提供直接的批量上传封装,因此需要自行实现文件遍历逻辑,但整体复杂度很低。
内容的提问来源于stack exchange,提问作者Matteo Bombelli
相关产品推荐
相关产品推荐

