En kombination af en ekspres-middleware (for at kontrollere godkendelsen af den bruger, der foretager anmodningen) og brugen af Node AWS SDK burde gøre tricket.
Her er et fuldstændigt eksempel med multer til upload.
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);
Dette er naturligvis kun delvist testet og mangler korrekt fejlhåndtering - men det burde forhåbentlig give dig en nogenlunde idé om, hvordan du implementerer det.