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.sstatic.net/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);
}
}
},
},
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"
}
]
}
});