【问题标题】:Upload a large number of files to AWS S3 at once一次将大量文件上传到 AWS S3
【发布时间】:2018-07-13 01:17:09
【问题描述】:

我有一个应用程序,需要将多个100,000 files(每个1MB)上传到S3 Bucket。我知道 S3 有上传大文件的 API,但想知道他们是否有上传大量文件的 API。

我目前正在使用putObject 并尝试使用upload API 将我的文件上传到 S3。问题是上传时间太长(浏览器超时后完成)并且使用大量内存(超过512MB允许的限制)。

保存文件的代码:

saveFile: async (fileUrl, data) => {
    await s3.putObject({
        Bucket: bucket,
        Key: fileUrl,
        Body: JSON.stringify(data)
    }).promise();
},

在另一个地方,我将 saveFile 放在这样的循环中:

for (let file of files) {
    await saveFile(file.url, file.data);
}

我搜索了一个解决方案,发现stream 可能有助于减少内存需求,但我想知道在时间方面有什么不同吗?如果是,我该如何实现?谢谢。

【问题讨论】:

    标签: node.js amazon-web-services express amazon-s3 file-upload


    【解决方案1】:

    我通常更喜欢使用managed upload API,而不是putObject 方法。它可以处理多块上传的大文件,而且它还支持流(您不能将流与 putObject 一起使用,因为该 API 需要总文件大小)。

    例如,从节点:

    const fs = require('fs');
    const AWS = require('aws-sdk');
    const s3 = new AWS.S3({});
    
    s3.upload({
      Bucket: 'xxx',
      Key: 'fileName.png',
      Body: fs.createReadStream('/home/bar/Desktop/fileName.png')
    }).promise(); // or callback
    

    这可能会解决您与内存相关的问题,但可能不会加快上传速度。 for 循环的问题在于它会一个接一个地连续上传对象。相反,您可以使用 await Promise.all([/* your list*/].map(/* ... */)),它将并行执行所有上传 - 但是 - 100,000 是一个太大的数字。

    我建议使用像async 这样的库,它有很多有用的方法来处理异步操作组。 例如,您可以使用 cargo 或 queue 方法,您的代码如下所示:

    const PARALLEL_UPLOADS = 10;
    const q = async.queue((task, callback) => {
      s3.upload({
        Bucket: 'xxx',
        Key: task.dest,
        Body: fs.createReadStream(task.src)
      }, callback)
    }, PARALLEL_UPLOADS);
    
    q.drain = function() {
        console.log('all items have been processed');
    };
    
    q.push([
        { src: 'image1.png', dest: 'images/image1.png' },
        { src: 'image2.png', dest: 'images/image2.png' },
    ]);
    

    这将上传您的所有文件,最多同时上传 10 个项目。

    希望这会有所帮助,

    【讨论】:

    • 谢谢你,西蒙娜。很高兴知道async,因为我最近使用了更多的 js。顺便说一句,很好的解释,我非常感谢。上面的 forEach 你说的,我觉得应该是串联运行吧?或者您从任何外部库/模块中提到了 forEach?
    • PS:它现在运行得非常快,有时会达到内存限制(1 或 2 次),但不像在循环中使用嵌套的 putObject 那样通常,同时利用它必须运行的内容最好的。非常漂亮的西蒙娜!
    • 很高兴我能提供帮助。当我写forEach 时,我实际上指的是普通的[ ].map,包裹在await Promise.all() 中。这将导致“并行”发出大量请求,它不会等待请求完成来处理下一个请求(因为 await 关键字在其中没有意义)。 上面的答案更新为引用 Promise.all 而不是 forEach
    【解决方案2】:
    const AWS = require('aws-sdk');
    const fs = require('graceful-fs'); // from node.js
    const path = require('path'); // from node.js
    const queue = require('async-promise-queue');
    const s3 = new AWS.S3();
    
    const pushS3 = (srcFolderPath, destFolderPath) => {
      const uploadPromise = [];
      console.log(`Pushing ${srcFolderPath} to S3`);
    
      const files = fs.readdirSync(srcFolderPath);
        if (!files || files.length === 0) throw new Error(`provided folder '${srcFolderPath}' is empty or does not exist.`);
    
      // for each file in the directory
      for (const fileName of files) {
        // get the full path of the file
        const filePath = path.join(srcFolderPath, fileName);
    
       // ignore if directory
       if (fs.lstatSync(filePath).isDirectory()) {
         continue;
       }
    
       uploadPromise.push({
         src: filePath,
         dest: `${destFolderPath}${fileName}`,
       });
      }
      const worker = queue.async.asyncify(task => s3.upload({
        Bucket: AWS_BUCKET,
        Key: task.dest,
        Body: fs.createReadStream(task.src),
      }).promise());
    
      return queue(worker, uploadPromise, 10000);
    };
    
    pushS3('sourcePath', 'destinationS3Path')
    .then(()=>{console.log('Sucessfully Transferred to S3');})
    .catch((err)=>{console.error(err);})
    

    承诺实施上述 Simone Lusenti 的解决方案。就我而言,我有 50000 多个奇怪的文件。我试图将这些文件从 AWS ECS 放到 S3。我之前有2个错误。 EMFILE too many files open 错误已通过 graceful-fs 模块和 AWS ECS 中的 Missing Credentials Error 使用 async-promise-queue 模块解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多