1
votes

I'm trying to upload multipart form data using multer. I'm using swagger express middleware for my APIs. Without swagger everything was working. But with swagger, file is not uploaded. There's no validation error, but it simply doesn't upload file. Here's some code that you may want to see:

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

upload function

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

So, the problem seems that file is undefined here since when I'm using swagger. Earlier it was fine. But now it returns status:success but image was never uploaded.

Am I doing something wrong?

1

1 Answers

0
votes

swaggerExpress uploading a file local/s3 successful

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