Reputation: 224
I realise there's quite a few resources online about this, but none seem to use a method I like.
Currently, I have a form with a lot of inputs that gets sent to the server when a "Submit" button is clicked. This is all sent via a json request using the normal AngularJS controller/service, and eventually handled by my ExpressJS router to store it in a MongoDB.
I want to add an input to select an image file to upload. Everything I find online seems to do it in a way that as soon as the user selects a file, its immediately copied to the server. Not what I want. Does anyone know if I can somehow upload the file when the "Submit" button is clicked? If so, where can I find information on this?
Thanks
Upvotes: 0
Views: 143
Reputation: 81
Take a look at this npm package: https://www.npmjs.com/package/express-fileupload
I chose to save the file on the filesystem but you can easily change it to store it in mongo
The router
router.post(‘/foo’, function (req, res, next) {
if (!req.files){
res.redirect(‘/foo’);
}
let file = req.files.file;
let fileName = req.files.file.name;
if(sys.isJSFile(fileName)){
//save to filesystem or mongodb
let filePath = path.join(‘./images’, fileName);
// Use the mv() method to place the file somewhere on your server
file.mv(filePath, function(err) {
if (err){
logger.error("Could not upload file: " + err);
res.redirect(‘/foo’);
} else {
res.redirect(‘/bar’);
}
}
});
The view
<form class="form-horizontal" action=“/foo” method="post" encType="multipart/form-data">
<div class="form-group">
<input class="form-control" type="file" name="file" />
</div>
<div class="form-group">
<input class="form-control" type="submit" value="Submit"/>
</div>
</form>
Upvotes: 1