how to save images with angular nodejs
There are two ways to save images.
1) store image in database by converting it to binary format.
2) copy image in your project folder then save image path in table.
------- 1st way with front end angular------
pass uploaded file in "handleFileInput" function.
saveImage(files: FileList) {
var file:File = files.item(0);
var myReader:FileReader = new FileReader();
myReader.onloadend = (e) => {
this.image = myReader.result;
}
myReader.readAsDataURL(file);
//convert to base64 ends
}
now you will get binary format image in this.image variable. save this converted image directly to database through API.
we can use "multer" to copy file in project folder.
const multer = require('multer');
var storage = multer.diskStorage({
destination: './images',
filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname)
}
});
const upload = multer({ storage })
//send your image with post request
app.post('/upload', upload.single('image'), (req, res) => {
if (req.file)
{
console.log("Done"); // Success
res.send({result:'success'})
}
else
{
res.status("409").json("No Files to Upload.");
}
});
would you be able to add a WebAPI code to consume data produced by method 1
ReplyDelete