node.js - 将图像上传到 S3 并读取 req.body 中的键值
问题描述
我有这个代码块可以将图像上传到 S3
这是图像上传控制器:
const multer = require('multer');
const multerS3 = require('multer-s3');
const AWS = require('aws-sdk');
let AWSConfig = require('./../config/awsconfig');
AWS.config.update({
accessKeyId: AWSConfig.S3_AKID,
secretAccessKey: AWSConfig.S3_SAK,
"region": AWSConfig.S3_REGION
});
exports.uploadWorkout = async (req, res) => {
req.setTimeout(0);
const s3 = new AWS.S3({ httpOptions: { timeout: 10 * 60 * 1000 }});
const singleUpload = multer({
storage: multerS3({
s3: s3,
bucket: AWSConfig.S3_BUCKET,
contentType: multerS3.AUTO_CONTENT_TYPE,
contentLength: req.body.length,
acl: 'public-read',
metadata: function(req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function(req, file, cb) {
cb(null, Date.now().toString()+'.'+file.originalname.split('.')[1]);
}
})
}).single('image');
await singleUpload(req, res, error => {
//const file = req.files; // files for array of files
const file = req.file; // file for single file
console.log("req.body >>>>>>>> ", req.body);
if(error) {
return res.status(400).send(error);
}
return res.status(200).send({imageurl: file.location});
});
}
这是主要的 App.js
// App.js
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(function(req, res, next) { //allow cross origin requests
res.setHeader("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Max-Age", "3600");
res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
next();
});
app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(cors());
// rest of the error handling code ......
module.exports = app;
邮差:
标题:
Content-Type: application/octet-stream
x-amz-meta-fieldname: image
Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vybm9sh3rd9s212ddsfzdDFAZ21ha....
图像被上传,我得到 imageurl 作为响应,但我无法从 Postman 获得 SomeKey 和 SomeValueSomeValueSomeValueSomeValue 。我得到的req.body
是空对象{}
,即来自console.log():
req.body >>>>>>>> {}
解决方案
推荐阅读
- java - 线程“主”java.util.NoSuchElementException 中的异常:在 java.util.Scanner.nextLine(Scanner.java:1540)处找不到行
- excel - Excel workbook ADO query to itself fails on first run if the file is opened programmatically
- java - Spring boot 从 1.5.22 升级到 2.3.4,MvcEndpoint.class 有问题
- python - 出现错误:调用DeleteObject操作时发生错误(AccessDenied):从python删除文件/文件夹时访问被拒绝
- javascript - 本地存储无法在待办事项应用 REACT 中存储复选框
- python - VSCode Jupyter 加载不正确的 python 版本
- amazon-web-services - 如何避免从两个 lambda 覆盖 dynamodb?
- jenkins - Jenkins Pipeline 中是否有任何显示重建信息的环境变量?
- mysql - MySQL事务不回滚会有什么影响?
- php - Laravel 419 页面过期