【问题标题】:NodeJs - User upload to s3NodeJs - 用户上传到 s3
【发布时间】:2014-02-14 20:16:08
【问题描述】:

我是 node.js 的新手,想要做以下事情:

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

因为我之前从未使用过 S3 或上传过一些东西 错误的想法 - 如果我错了,请纠正我。

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

感谢您的帮助!

【问题讨论】:

    标签: node.js file-upload amazon-s3


    【解决方案1】:

    首先我建议查看 NodeJS 的 knox 模块。它来自相当可靠的来源。 https://github.com/LearnBoost/knox

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

    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
        })
    })
    

    【讨论】:

    • 必须指定我的区域,现在一切正常!谢谢
    猜你喜欢
    • 2021-11-28
    • 2019-12-13
    • 2015-03-17
    • 1970-01-01
    • 2017-03-22
    • 2020-05-11
    • 2022-11-05
    • 1970-01-01
    • 2021-08-03
    相关资源
    最近更新 更多