Profile Picture - pmvdbijl7/matching-app GitHub Wiki

To make the profiles of the users a bit more personal, we have added a feature that allows users to set and change their profile picture. This way, other users can see who they are matching with. We added this function using the multer package.

uploadController.js

We have created a separate uploadController to configure everything related to file uploads in it. As you can see in the code below, we first determine where all uploads will be saved and under what name the file should be saved.

// Set Uploads Storage Engine
const uploadStorage = multer.diskStorage({
	// Determine uploads save
	destination: (req, file, cb) => {
		cb(null, 'public/uploads');
	},
	// Determine file name
	filename: (req, file, cb) => {
		cb(
			null,
			file.fieldname + '-' + Date.now() + path.extname(file.originalname)
		);
	},
});

We then pass this function to multer and determine the name of the input field from which multer should save this file.

// File Upload
const upload = multer({ storage: uploadStorage }).single('profile_image');

Routes

The last thing we have to do is add the upload function to the route where we want to save this profile picture. In our case we imported these when editing a profile.

router.post('/account/edit',
	verifyAccess,
	uploadController.upload,
	accountController.editPost
);