我对node.js很新,并希望执行以下操作:
因为在我可能有一些之前我从未使用过S3或完成上传 错误的想法 - 如果我错了,请纠正我。
所以在我看来,原始文件名应保存到数据库中并返回下载,但S3上的文件应重命名为我的数据库条目id以防止覆盖文件。接下来,文件应该流式传输还是什么?我从来没有这样做但是在服务器上缓存文件然后将它们推送到S3似乎并不聪明,是吗?
感谢您的帮助!
答案 0 :(得分: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
})
})