Multer文件上传不适用于swaggerExpress

时间:2017-07-30 06:29:52

标签: node.js express swagger multer

我尝试使用 multer 上传多部分表单数据。我在我的API中使用了swagger express中间件。没有招摇,一切都在发挥作用。但随着招摇,文件不上传。没有验证错误,但它根本没有上传文件。以下是您可能希望看到的一些代码:

app.js

SwaggerExpress.create(config, function(err, swaggerExpress) {
  if (err) { throw err; }
  swaggerExpress.register(app);
  var port = 8850;
    https.createServer(options, app).listen(port, function () {
        console.log('Bus993 server started @ %s!', port);
    });
});

上传功能

function uploadImage(req, res, multer){
    console.log("here", req.files);
    //ABOVE SHOWS A VALID FILE
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            console.log("fILE", file);
            //THIS IS NOT PRINTED
            cb(null, '../../public/images');
        },
        filename: function (req, file, cb) {
            console.log(file);
            //THIS IS NOT PRINTED
            cb(null, file.originalname.replace(/[.]{1}[a-zA-Z]+$/, "") + '_' + moment().format('X') + getExtension(file));
        }
    });


    var upload = multer({storage: storage, fileFilter: fileFilter}).single('imageFile');

    upload(req, res, function (err) {
        if (err) {
            res.status(422).json(
                {
                    status: "error",
                    data: {error: err.message},
                    message: "Image upload failed."
                }
            );
        } else {
            res.status(200).json(
                {
                    status: "success",
                    data: "",
                    message: "Image uploaded successfully."
                }
            );
        }
    });


    function fileFilter(req, file, cb) {
        console.log("fILE", file);
        if ((file.mimetype != 'image/jpeg' && file.mimetype != 'image/png' &&         file.mimetype != 'image/gif') || file.size > 8000) {
            cb(new Error('Invalid file.'), false);
        } else {
            cb(null, true);
        }
    }


    function getExtension(file) {
        var res = '';
        if (file.mimetype === 'image/jpeg') res = '.jpg';
        if (file.mimetype === 'image/png') res = '.png';
        if (file.mimetype === 'image/gif') res = '.gif';
        return res;
    }
}

所以,问题似乎是文件在这里未定义,因为我使用了swagger。早些时候很好。但现在它返回status:success,但图像从未上传过。

我做错了吗?

1 个答案:

答案 0 :(得分:0)

swaggerExpress上传文件local / s3成功

following setups are:
1. in swagger file(yaml)
/s3/upload:
x-swagger-router-controller: s3/upload
post:
  operationId: upload
  tags:
  - S3
  consumes:
    - multipart/form-data
  parameters:
    - in: formData
      name: file
      description: The file to upload
      type: file

 2.add extra middleware
 SwaggerExpress.create(config, function(err, swaggerExpress) {
   if (err) { throw err; }
   // install middleware
   app.use(SwaggerUi(swaggerExpress.runner.swagger));

   // install extra middleware
   app.use(function (req, res, next) {
    if(req.file){
      req.files = req.file  
    }else{
      req.files = {}
    }
    next();
  });
  // install middleware
  swaggerExpress.register(app);
  console.log("Listening on port: "+ port)
  app.listen(port);
  });
  3.controller using multer,multerS3 and aws-sdk

  define middleware before controller
  s3 object

  const uploadFile = multer({
    storage: multerS3({
    s3: s3,
    bucket: 'bucket_name',
    metadata: function (req, file, cb) {
     cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
     cb(null, file.originalname)
    }
  })
 }).fields([{name: "file"}])

 controller.upload = async function(req, res, next){
 console.log("---------upload---------------");
 try{
   uploadFile(req, res, function (error) {
     if (error) {
       console.log(error);
         res.json({
         result: "Error",
         status: false
      })
     }else{
       console.log('File uploaded successfully.',req.files);
       res.json({
       result: req.files.file[0],
       status: true
     })
   }

  });

  }catch(e){
    res.json({
    message: "Error"
  })
 }
}

enter image description here