I'm working with image upload
in angular. The image uploading part works fine but now the problem is I should rename the image before uploading.
I want to know if it will be easier to do so from the fronend
or from the backend
.
The framework used for frontend is angular
and backend is nodejs
.
Hope someone will help me with this since I dont have much experience with this framework
Thank you.
CodePudding user response:
This is an very opinionated question. On the frontend I imagine your using some sort of form to attach the file. On frontend it could be as easy as this:
formData.append('userpic', myFileInput.files[0], 'chris.jpg');
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
CodePudding user response:
i can show you an example of code i use to upload a profile image in nodeJS express backend as joosep has given an example for the frontend. my code is as follows:
exports.uploadImage = (req, res, next) => {
const url = req.protocol '://' req.get('host')
profileRepository
.findOne({ _id: req.params.id })
.then((response) => {
const fetchedUser = response;
fetchedUser.imagePath = url '/images/' req.file.filename;
profileRepository
.updateOne({ _id: req.params.id }, fetchedUser)
.then((response) => {
return res.status(200).json({
message: 'profileimage updated',
});
})
.catch((error) => {
return res.status(500).json({
message: 'uploading image failed',
});
});
})
.catch((error) => {
return res.status(404).json({
message: 'fetching user failed',
});
});
};
as you can see i set the name for the image when assigining an imagepath for the fetchedUser. in the example i am just using the filename which comes from the frontend request but you can use any name/string you want instead :)
hopefully this can help you choosing the best implementation for your use case