sql >> Databáze >  >> NoSQL >> MongoDB

Předávat soubory z Amazon S3 přes server NodeJS bez odhalení S3 URL?

Kombinace expresního middlewaru (pro kontrolu autorizace uživatele zadávajícího požadavek) a použití Node AWS SDK měl by stačit.

Zde je úplný příklad použití multer pro nahrání.

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

Je zřejmé, že je to jen částečně otestováno a chybí správné zpracování chyb – ale doufejme, že by vám to mělo poskytnout přibližnou představu o tom, jak to implementovat.



  1. Konzistence čtení-vašeho-zápisu v Mongodb

  2. Agregace s více kritérii a shoda součtů na základě klíče počtu

  3. Vložení objektu momentjs do kolekce Meteor

  4. Dotaz na časové období pro databázi tweetů MongoDB selhal