0

I am new to the Moleculer framework and need to upload a file from an API request body to MongoDB using an action handler. I have been able to upload files using Multer with Express, but I need to use only the Moleculer framework. When I run the action handler, the "req" parameter doesn't take the file from the request body and it's always undefined. I need help finding a way to make the file come to the action handler.

(https://i.stack.imgur.com/Xv7YP.png)

actions: {
    create: {
        rest: "POST /",
        async handler(ctx) {
            try {
                console.log("Params are: " + ctx.params.file);
                console.log("Meta is: " + ctx.meta.file);
                console.log("File is: " + ctx.file);
            } catch(err) {
                console.log("Error: " + err);
            }
        }
    },
},

1 Answers1

0

The file upload is handled as a Stream in actions, but you should configure it in the route settings. In the documentation you can find information about it: https://moleculer.services/docs/0.14/moleculer-web.html#File-upload-aliases

E.g:

module.exports = {
    mixins: [ApiGateway],
    settings: {
        path: "/upload",

        routes: [
            {
                path: "",

                aliases: {
                    // File upload from HTML multipart form
                    "POST /": "multipart:file.save",
                    
                    // File upload from AJAX or cURL
                    "PUT /:id": "stream:file.save",

                    // File upload from HTML form and overwrite busboy config
                    "POST /multi": {
                        type: "multipart",
                        // Action level busboy config
                        busboyConfig: {
                            limits: { files: 3 }
                        },
                        action: "file.save"
                    }
                },

                // Route level busboy config.
                // More info: https://github.com/mscdex/busboy#busboy-methods
                busboyConfig: {
                    limits: { files: 1 }
                    // Can be defined limit event handlers
                    // `onPartsLimit`, `onFilesLimit` or `onFieldsLimit`
                },

                mappingPolicy: "restrict"
            }
        ]
    }
});
Icebob
  • 1,132
  • 7
  • 14
  • Hi, thanks for the solution this worked but it stores the file to a temporary path. Can we have this file store in a different path or store it in Mongo dB directly in the form of buffer. If so could you help me with the code to achieve that – Lalith Rajendran Jun 17 '23 at 08:58