
# 批量上传对象(Node.js SDK)
![](https://support.huaweicloud.com/sdk-nodejs-devg-obs/public_sys-resources/notice_3.0-zh-cn.png)
开发过程中，您有任何问题可以在GitHub上[提交issue](https://github.com/huaweicloud/huaweicloud-sdk-nodejs-obs/issues)，或者在[华为云对象存储服务论坛](https://bbs.huaweicloud.com/forum/forum-620-1.html)中发帖求助。
您可以通过以下接口在上传时使用批量操作：
- [文本上传(Node.js SDK)](https://support.huaweicloud.com/sdk-nodejs-devg-obs/obs_29_0402.html)
- [流式上传(Node.js SDK)](https://support.huaweicloud.com/sdk-nodejs-devg-obs/obs_29_0403.html)
- [文件上传(Node.js SDK)](https://support.huaweicloud.com/sdk-nodejs-devg-obs/obs_29_0404.html)
- [追加上传(Node.js SDK)](https://support.huaweicloud.com/sdk-nodejs-devg-obs/obs_29_0409.html)
#### 示例代码
本示例用于批量上传本地目录中的文件到OBS指定桶。您可以通过递归扫描本地目录， 再以指定并发数并发上传，文件按相对路径生成OBS对象Key，适用于本地文件批量迁移、数据备份上传等场景。
```
// 引入obs库
// 使用npm安装
const ObsClient = require("esdk-obs-nodejs");
// 使用源码安装
// var ObsClient = require('./lib/obs');
// 创建ObsClient实例
const obsClient = new ObsClient({
  // 推荐通过环境变量获取AKSK，这里也可以使用其他外部引入方式传入，如果使用硬编码可能会存在泄露风险
  // 您可以登录访问管理控制台获取访问密钥AK/SK，获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // 【可选】如果使用临时AK/SK和SecurityToken访问OBS，同样建议您尽量避免使用硬编码，以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK，也可以使用其他外部引入方式传入
  // security_token: process.env.SECURITY_TOKEN,
  // endpoint填写Bucket对应的Endpoint, 这里以华北-北京四为例，其他地区请按实际情况填写
  server: "https://obs.cn-north-4.myhuaweicloud.com",
});
// 本地待上传目录
const localUploadDir = "./uploads";
// OBS中的目标前缀
const obsPrefix = "uploaded/";
/**
 * 递归获取目录下的所有文件
 */
function getAllFiles(dir, fileList = []) {
  const files = fs.readdirSync(dir);
  for (const file of files) {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    if (stat.isDirectory()) {
      getAllFiles(filePath, fileList);
    } else {
      fileList.push(filePath);
    }
  }
  return fileList;
}
/**
 * 批量上传对象
 */
async function batchUpload() {
  try {
    const bucketName = "examplebucket";
    // 获取本地待上传文件列表
    if (!fs.existsSync(localUploadDir)) {
      console.log(`Local directory ${localUploadDir} does not exist`);
      return;
    }
    const filesToUpload = getAllFiles(localUploadDir);
    if (filesToUpload.length === 0) {
      console.log("No files found to upload");
      return;
    }
    console.log(`Found ${filesToUpload.length} files, starting batch upload...`);
    // 使用Promise.allSettled并行上传（限制并发数避免资源耗尽）
    const concurrency = 5; // 并发数
    let completed = 0;
    let successCount = 0;
    let failCount = 0;
    for (let i = 0; i < filesToUpload.length; i += concurrency) {
      const batch = filesToUpload.slice(i, i + concurrency);
      const uploadPromises = batch.map(async (filePath) => {
        // 计算OBS中的对象Key
        const relativePath = path.relative(localUploadDir, filePath);
        const objectKey = obsPrefix + relativePath.replace(/\\/g, "/");
        const uploadParams = {
          Bucket: bucketName,
          Key: objectKey,
          SourceFile: filePath,
        };
        const result = await obsClient.putObject(uploadParams);
        if (result.CommonMsg.Status <= 300) {
          console.log(`[${++completed}/${filesToUpload.length}] File [${filePath}] uploaded successfully, ETag: ${result.InterfaceResult.ETag}`);
          return true;
        } else {
          console.log(`[${++completed}/${filesToUpload.length}] File [${filePath}] upload failed: ${result.CommonMsg.Message}`);
          return false;
        }
      });
      const results = await Promise.allSettled(uploadPromises);
      results.forEach((r) => {
        if (r.status === "fulfilled" && r.value) {
          successCount++;
        } else {
          failCount++;
        }
      });
    }
    console.log(`Batch upload complete: ${successCount} succeeded, ${failCount} failed`);
  } catch (error) {
    console.log("Client exception:");;
    console.log(error);
  }
}
batchUpload();
```
