エクスプレスミドルウェア(リクエストを行ったユーザーの承認を確認する)とNode AWS SDKの使用は、このトリックを行う必要があります。
アップロードには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);
明らかにこれは部分的にしかテストし、適切なエラー処理の欠けている - それがうまくいけば、それはあなたにそれを実装する方法の大まかなアイデアを与える必要があります。
ありがとうございます!私はアップロードとダウンロードのための簡単なヘルパー関数を提供するs3ライブラリを使ってこれを始めることにしましたが、私はこの答えを他のものについて参考にします。 – Aron
あなたは[node-s3-client](https://github.com/andrewrk/node-s3-client)を参照していますか?はいの場合、私はあなたに警告する必要があります、私はそれで非常に悪い経験をしてきました。例えば、[issue#127](https://github.com/andrewr/node-s3-client/issues/127)、[issue#121](https://github.com/andrewrk/node-s3-クライアント/問題/ 121) – christophetd
ああ。はい、そうです。 Hmmm:/ OKプロトタイプフェーズではこれに固執しますが、フェーズ2では自分のやり方でやります。 – Aron