首页 > 解决方案 > 将图像上传到 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 >>>>>>>> {}

标签: node.jsamazon-web-servicesexpressamazon-s3

解决方案


推荐阅读