The integration between Multer file uploads and SwaggerExpress is not functioning properly

I'm encountering an issue while attempting to upload multipart form data using multer. I have integrated swagger express middleware for my APIs. Strangely, everything was functioning correctly before implementing swagger. However, after integrating swagger, the file does not get uploaded. There are no validation errors being displayed, but the file simply fails to upload. Below is some relevant code that you may find helpful:

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

It appears that the issue lies in the fact that file is undefined when using swagger. Previously, this was not a problem. Now, even though it returns a status of success, the image is still not uploaded.

Could there be an error in my implementation?

Answer №1

Successfully uploaded a file to local/s3 using SwaggerExpress

The following setups are necessary for uploading a file:
1. In the 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. Adding 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 the controller.
Create an 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"}])

The controller.upload function is responsible for handling the file upload process asynchronously. It logs the progress and returns appropriate responses based on the outcome.

<a href="https://i.stack.imgur.com/oK1S8.png" rel="nofollow noreferrer">View the image here</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges arise when trying to display real-time Firebase data in a tabular format

I established a Firebase RealTime database with the following Values: Table: tutorial-vue-eb404 Root: other children year, author, publisher, title Using npm, I initialized my project The configuration was set up by creating firebase.js import Firebase ...

Utilizing Async/Await with an Unassigned Object

I'm facing a puzzling issue with an async/await function that refuses to assign to an object. Despite displaying the expected results in the console, when it comes to actually assigning to the object, it fails to do so. Let me elaborate below: Here&a ...

Guide on executing a findOne function inside another findOne function in Node.js using mongoose

My current project involves writing a REST API for a website that deals with users and flashcards. I have opted to use a MERN stack for this development. The mongodb structure is outlined as follows: //FlashCardSchema const flashcardSchema = new Schema({ ...

Nullify the unfulfilled fetch call

When a value is entered in the search bar on the webpage, it gets added to a URL and used to retrieve JSON data. Everything works smoothly, but if a value is inputted that the API doesn't have information for, a null response is returned. The questio ...

`MongoDB impatient for query outcome`

Upon trying to pass the 'db' from my server.js file, where I establish a connection with MongoClient, to routes/api.js for post requests, I encountered an issue. The error message I consistently receive is: TypeError: Cannot read property &apo ...

operating smoothly on local host, encountering issues on firebase

When I access the '/form' directory on my local host, the page renders correctly. However, when I deploy it on Firebase, I get a 404 error. Even if I change the 404 file itself, I still can't see any changes. I have tried clearing the cache ...

The ACL system in Node.js that is based on resources

I am in the process of setting up a basic Access Control system in Node, and I am seeking advice on the most effective approach for what I want to achieve. Currently, I am utilizing Node ACL, but it's not entirely clear how to block access based on s ...

Unexpected silence from the Express web server

I am currently in the process of setting up my Angular application for Server Side Rendering using Angular Universal. Below is the JS file that has been generated by Angular Universal, with minor modifications made to the path and port: import 'zone ...

Efficiently generating multiple new documents in MongoDB using Node.js

I am looking to insert a large amount of data into mongoDB using the following code snippet: const data = [{user : "1",password: "1"}, {user : "2",password: "2"}, {user : "3",password: "3"}, // up ...

What steps can be taken to ensure MacOS can detect installed packages after the deletion of `/usr/local/lib` and `/usr/local/include` directories?

While feeling very tired, I attempted to uninstall my node.js due to some issues and ended up accidentally deleting two important folders, /usr/local/lib and /usr/local/include, on my Mac Mojave! After reinstalling the OS, much to my surprise, all my pers ...

Saving the initial and final days of each month in a year using javascript

I am trying to create an array of objects that contain the first and last day of each month in the year. I have attempted a solution but have hit a roadblock and cannot achieve the desired results. module.exports = function () { let months_names = ["j ...

Navigating through Node's asynchronous behavior

I am currently developing a web scraper that gathers data about various shirts from a specific website. I have successfully set up all the necessary NPM packages in Node.js to scrape the information and save it to a CSV file. However, I have encountered ...

The body of the POST request appears to be void of any

Whenever I make a request using curl or hurl, an issue arises. Despite req.headers['content-length'] showing the correct length and req.headers['content-type'] being accurate, req.body returns as {}. Below is the Hurl test: POST http:/ ...

Leveraging branch codes found within package.json from gitrepositories

Our team is currently working on a node.js application and I am using a package created by one of my colleagues that has been published to npm. Now, my colleague has created a new Git branch (referred to as "second"). Is there a way for me to include this ...

"Concealing Querystrings in Node.js and AJAX: A Step-by-Step

I want to create a simple login form using the ajax Post method. However, I am having issues with the querystring still appearing in the URL. Can anyone help me resolve this issue? Thank you for any assistance! [ https://i.stack.imgur.com/R76O4.png http ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

Applying comparison operators to query strings in Express for a more refined filtering process

When dealing with a resource in the database, I am familiar with utilizing the mongodb npm package within my express app to apply filters like $gt, $lt, etc. This allows me to specifically retrieve values based on the desired filter criteria. In addition, ...

The issue at hand is the lack of execution for the Mocha Chai `.end()`

I have encountered an issue while trying to write a Mocha chai test for a Nodejs API that was previously tested using Supertest. Strangely, the test always passes even when I intentionally specify wrong expected parameters. Below is the code snippet of th ...

Transform stereo sound to mono using JavaScript

Recently, I encountered an audio file in stereo with a .raw extension that needs to be converted into mono using Node. Despite my efforts, I haven't been successful in finding examples or libraries outlining the process. Any assistance on this matter ...

Extremely sluggish updating efficiency

As I parse through a CSV file, I aim to verify if the corresponding entry exists in the database for each row. If it does exist, I want to update it; if it doesn't, I want to create a new entry. The process seems to be sluggish, averaging only around ...