Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 从Amazon S3通过NodeJS服务器传递文件而不暴露S3 URL?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将S3文件存储集成到我的NodeJS应用程序中. This tutorial解释如何直接上传到S3是非常好的,但它不适合我的需要,因为我希望文件只能通过我的网络应用程序的API访问.我不希望文件在他们的S3网址上公开,我只希望它们可以通过例如/ api / files /< user_id> /< item_id> /< filename>来获得.

我希望下载通过我的API的原因是我可以检查是否允许用户查看此特定文件.

我希望上传通过我的服务器的原因是我知道哪个< item_id>分配文件名,因为它与MongoDB _id属性相同.如果我在第一个项目有Mongo _id之前将文件上传到S3,则无法执行此操作.

我看过但是找不到一个简单的教程,如何通过我的NodeJS应用程序将文件从S3传输到客户端,反之亦然.

谢谢

解决方法

快速中间件(用于检查发出请求的用户的授权)和使用 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"),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",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);

显然,这只是部分测试,缺乏正确的错误处理 – 但希望它能让你大致了解如何实现它.

大佬总结

以上是大佬教程为你收集整理的node.js – 从Amazon S3通过NodeJS服务器传递文件而不暴露S3 URL?全部内容,希望文章能够帮你解决node.js – 从Amazon S3通过NodeJS服务器传递文件而不暴露S3 URL?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。