s3 文件服务器,node.js – 从Amazon S3通过NodeJS服务器传递文件而不暴露S3 URL?

该博客提供了一个使用Node.js、Express、Multer和AWS SDK的示例,展示了如何创建一个中间件来检查用户授权,并实现文件上传到S3以及从S3下载的流程。示例中包含了错误处理的基本框架,但强调了需要进一步完善错误处理部分。
摘要由CSDN通过智能技术生成

快速中间件(用于检查发出请求的用户的授权)和使用

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值