我正在尝试将 S3 文件存储集成到我的 NodeJS 应用程序中。本教程 https://devcenter.heroku.com/articles/s3-upload-node解释如何上传directlyto S3 非常好,但它不适合我的需求,因为我希望这些文件只能通过我的网络应用程序的 API 访问。我不希望这些文件在其 S3 URL 上公开可用,我只想通过例如/api/files/<user_id>/<item_id>/<filename>
.
我想要的理由下载通过我的 API 是为了检查用户是否有权查看此特定文件。
我想要的理由uploads通过我的服务器以便我知道哪个<item_id>
分配文件名,因为这将与其 MongoDB 相同_id
财产。如果我在该项目具有 Mongo 之前将文件上传到 S3,我将无法执行此操作_id
首先。
我已经查看过,但找不到关于如何通过 NodeJS 应用程序将文件从 S3 流式传输到客户端(反之亦然)的简单教程。
谢谢
快速中间件(用于检查发出请求的用户的授权)和使用节点AWS SDK https://github.com/aws/aws-sdk-js应该可以解决问题。
这是一个完整的例子,使用multer https://github.com/expressjs/multer用于上传。
var express = require('express');
var app = express();
var router = express.Router();
var multer = require('multer');
var upload = multer({
dest: "tmp/"
});
var fs = require('fs');
var async = require('async');
var AWS = require('aws-sdk');
// Configure AWS SDK here
var s3 = new AWS.s3({
params: {
Bucket: 'xxx'
}
});
/**
* Authentication middleware
*
* It will be called for any routes starting with /files
*/
app.use("/files", function (req, res, next) {
var authorized = true; // use custom logic here
if (!authorized) {
return res.status(403).end("not authorized");
}
next();
});
// Route for the upload
app.post("/files/upload", upload.single("form-field-name"), function (req, res) {
var fileInfo = console.log(req.file);
var fileStream = fs.readFileSync(fileInfo.path);
var options = {
Bucket: 'xxx',
Key: 'yyy/'+fileName,
Body: fileStream
};
s3.upload(options, function (err) {
// Remove the temporary file
fs.removeFileSync("tmp/"+fileInfo.path); // ideally use the async version
if (err) {
return res.status(500).end("Upload to s3 failed");
}
res.status(200).end("File uploaded");
});
});
// Route for the download
app.get("/files/download/:name", function (req, res) {
var fileName = req.params.name;
if (!fileName) {
return res.status(400).end("missing file name");
}
var options = {
Bucket: 'xxx',
Key: 'yyy/'+fileName
};
res.attachment(fileName);
s3.getObject(options).createReadStream().pipe(res);
});
app.listen(3000);
显然这只是部分测试并且缺乏适当的错误处理 - 但希望它能让您大致了解如何实现它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)