There are two ways;
- store your image in base64 in your DB (check about this post : BASE64 to image angular 2)
- Front-side, get the file with file upload, appends it to a FormData object.
If it's a simple upload, you can append this way :
FormData.append('upload', upload, extraParam to define the file name);
If it's a multiple upload, this way :
for (let i = 0; i < files.length; i++) {
FormData.append('uploads[]', files[i], extraParam to define the file name);
}
Then, in the back-side, it's preferable to use multer (https://github.com/expressjs/multer)
There is a sample for multiple uploads :
const multer = require('multer');
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpeg',
'image/jpg': 'jpg'
};
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error('Invalid mime type');
if(isValid) {
error = null;
}
cb(error, "backend/images/photos");
},
filename: (req, file, cb) => {
const name = file.originalname.toLowerCase().split(' ').join('-');
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, name + '-' + Date.now() + '.' + ext);
}
});
module.exports = multer({storage: storage}).array("uploads[]", numberOfMaxUploads);
And there is for a simple upload :
const multer = require('multer');
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpeg',
'image/jpg': 'jpg'
};
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error('Invalid mime type');
if(isValid) {
error = null;
}
cb(error, "backend/images/photos");
},
filename: (req, file, cb) => {
const name = file.originalname.toLowerCase().split(' ').join('-');
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, name + '-' + Date.now() + '.' + ext);
}
});
module.exports = multer({storage: storage}).single("image");
There, my multer package is called as a middleware on my route on the back-end. You can do it this way :
const extractFile(s) = require('../middlewares/files/extractFile');
router.post("", extractFile(s), nextCall(Middleware or controller.method);