How to upload file using swagger-express-mw and express?
Although this being an old question here is how you can do it. We are using the express-fileupload
npm module here which makes our life easier. And below is a simple snippet to upload and save the file to our server, the swagger yaml stays the same.
//import the module const fileUpload = require('express-fileupload'); // Add this in express setup app.use(fileUpload()); // Your controller function, where you will get the file and store it as needed function uploadStudentPic(req: any, res: any, next: any) { var startup_image = req.files.imageFile; var fileName = startup_image.name; startup_image.mv(__dirname + '/images/' + fileName, function (err: any) { if (err) { res.status(500).send(err); } res.json({ "message": "File Uploaded" }); }); }
note: The above code is for a single & simple use case, you may need to do some more configurations based on your requirements. If you simply want to upload a file and store it on the server this should work.
An important thing to note here that swagger does not have to know which module we are using, OR nor does swagger provide for an inbuilt facility to upload an image.
What we are doing in declaring our API as in the question, more specifically these line ...
parameters: - in: formData name: imageFile type: file description: The file to upload. required: true
... is specifying that the above POST API expects a parameter named imageFile
which should be a file and is required by this API to function. And if the swagger validator middleware is enabled in your express & swagger-node configuration, our API will validate the incoming request and respond with a 400 Bad Request
error in case the file is not uploaded.
If you want a sample configuration of swagger-node
, swagger-tools
with swagger express middleware, you can find some details in this answer posted by me ( sorry for publicizing :P )