NodeJs - 用户上传到s3

zim*_*t28 2 file-upload amazon-s3 node.js

我对node.js很新,并且想要做以下事情:

  • 用户可以上传一个文件
  • 上传应保存到亚马逊s3
  • 文件信息应保存到数据库中
  • 脚本不应限于特定的文件大小

因为在我可能有一些错误的想法之前我从未使用过S3或完成上传 - 请纠正我,如果我错了.

因此,在我看来,原始文件名应保存到数据库中并返回下载,但S3上的文件应重命名为我的数据库条目ID,以防止覆盖文件.接下来,文件应该流式传输还是什么?我从来没有这样做但是在服务器上缓存文件然后将它们推送到S3似乎并不聪明,是吗?

谢谢你的帮助!

igo*_*lov 5

首先,我建议看看NodeJS的knox模块.它来自非常可靠的来源.https://github.com/LearnBoost/knox

我在下面为Express模块​​编写了一个代码,但是如果你不使用它或使用其他框架,你仍然应该理解基础知识.看一下代码中的CAPS_CAPTIONS,你想根据你的需要/配置来改变它们.另请阅读评论以了解代码段.

app.post('/YOUR_REQUEST_PATH', function(req, res, next){
    var fs = require("fs")
    var knox = require("knox")
    var s3 = knox.createClient({
        key: 'YOUR PUBLIC KEY HERE' // take it from AWS S3 configuration
      , secret: 'YOUR SECRET KEY HERE' // take it from AWS S3 configuration
      , bucket: 'YOUR BUCKET' // create a bucket on AWS S3 and put the name here. Configure it to your needs beforehand. Allow to upload (in AWS management console) and possibly view/download. This can be made via bucket policies.
    })
    fs.readFile(req.files.NAME_OF_FILE_FIELD.path, function(err, buf){ // read file submitted from the form on the fly
        var s3req = s3.put("/ABSOLUTE/FOLDER/ON/BUCKET/FILE_NAME.EXTENSION", { // configure putting a file. Write an algorithm to name your file
              'Content-Length': buf.length
            , 'Content-Type': 'FILE_MIME_TYPE'
        })
        s3req.on('response', function(s3res){ // write code for response
            if (200 == s3res.statusCode) {
                // play with database here, use s3req and s3res variables here
            } else {
                // handle errors here
            }
        })
        s3req.end(buf) // execute uploading
    })
})
Run Code Online (Sandbox Code Playgroud)