简体   繁体   English

Stream 使用 NodeJS+Express, aws-sdk 直接文件到 s3

[英]Stream File Directly to s3 using NodeJS+Express, aws-sdk

I want to upload some large files directly to s3 via the browser with NodeJS, it is unclear how to prepare this file for upload to s3.我想通过带有 NodeJS 的浏览器将一些大文件直接上传到 s3,目前还不清楚如何准备这个文件以上传到 s3。 There might be a better module (like Knox) to handle this case but I am not sure.可能有更好的模块(如 Knox)来处理这种情况,但我不确定。 Any thoughts?有什么想法吗?

File Object档案 Object

  file: { 
     webkitRelativePath: '',
     lastModifiedDate: '2013-06-22T02:43:54.000Z',
     name: '04-Bro Safari & UFO! - Animal.mp3',
     type: 'audio/mp3',
     size: 11082039 
  }

S3 putObject S3 put对象

var params = {Bucket: 'bucket_name/'+req.user._id+'/folder', Key: req.body['file']['name'], Body: ???};
s3.putObject(params, function(err, data) {
    if (err)
      console.log(err);
    else
      console.log("Successfully uploaded data to myBucket/myKey");
});    

Streaming is now supported ( see docs ), simply pass the stream as the Body : 现在支持Streaming( 参见docs ),只需将流作为Body传递:

var fs = require('fs');
var someDataStream = fs.createReadStream('bigfile');
var s3 = new AWS.S3({ params: { Bucket: 'myBucket', Key: 'myKey' } });
s3.putObject({ Body: someDataStream, ... }, function(err, data) {
  // handle response
})

The s3.putObject() method does not stream, and from what I see, the s3 module doesn't support streaming. s3.putObject()方法不会流式传输,从我看到的情况来看,s3模块不支持流式传输。 However, with Knox , you can use Client.putStream() . 但是,使用Knox ,您可以使用Client.putStream() Using the file object from your question, you can do something like this: 使用您问题中的文件对象,您可以执行以下操作:

var fs = require('fs');
var knox = require('knox');

var stream = fs.createReadStream('./file');
var client = knox.createClient({
  key: '<api-key-here>',
  secret: '<secret-here>',
  bucket: 'learnboost'
});

var headers = {
  'Content-Length': file.size,
  'Content-Type': file.type
};

client.putStream(stream, '/path.ext', headers, function(err, res) {
  // error or successful upload
});

One option is to use multer-s3 instead: https://www.npmjs.com/package/multer-s3 . 一种选择是使用multer-s3代替: https ://www.npmjs.com/package/multer-s3。

This post has some details also: Uploading images to S3 using NodeJS and Multer. 这篇文章还有一些细节: 使用NodeJS和Multer将图像上传到S3。 How to upload whole file onFileUploadComplete 如何上传整个文件onFileUploadComplete

Your code isn't streaming. 您的代码不是流媒体。 You need to see a call to pipe somewhere or at least code to pipe by hand by using data event handlers. 您需要通过使用data事件处理程序来查看对某个地方的pipe调用,或者至少需要手动管道代码。 You are probably using the express bodyParser middleware, which is NOT a streaming implementation. 您可能正在使用express bodyParser中间件,它不是流式实现。 It stores the entire request body as a temporary file on the local filesystem. 它将整个请求正文存储为本地文件系统上的临时文件。

I'm not going to provide specific suggestions because of the promising results I got from a web search for "node.js s3 stream". 我不打算提供具体的建议,因为我从网络搜索“node.js s3 stream”获得了有希望的结果。 Spend 5 minutes reading, then post a snippet that is at least an attempt at streaming and we can help you get it right once you have something in the ballpark. 花5分钟阅读,然后发布一个至少尝试流式传输的片段,一旦你在球场有什么东西我们可以帮助你把它弄好。

The v3, the PutObjectCommand can not write file stream to S3. v3中,PutObjectCommand无法将文件stream写入S3。 We need to use the @aws-sdk/lib-storage library for uploading buffers and streams.我们需要使用@aws-sdk/lib-storage库来上传缓冲区和流。

Example:例子:

const upload = async (fileStream) => {
    const uploadParams = {
        Bucket    : 'test-bucket',
        Key    : 'image1.png',
        Body: fileStream,
    }

    try {
        const parallelUpload = new Upload({
            client: s3Client,
            params: uploadParams,
        });

        console.log('Report progress..')
        parallelUpload.on("httpUploadProgress", (progress) => {
            console.log(progress);
        });

        await parallelUpload.done();
    } catch (e) {
        console.log(e);
    }
}

Ref - https://github.com/aws/aws-sdk-js-v3/blob/main/UPGRADING.md#s3-multipart-upload参考 - https://github.com/aws/aws-sdk-js-v3/blob/main/UPGRADING.md#s3-multipart-upload

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM