I'm submitting a form on an Angular build front-end. The form has both normal text input fields and a file upload function. I POST both the text input fields to my NodeJS API as a JSON object "contact", as well as the file as a new FormData as such:
// 'contact' defined above as a JSON object
// 'profilePic' set from event.target.files[0] in a listener function
const profilePicData = new FormData();
profilePicData.append('file', profilePic);
return this.http
.post<ContactResponseData>('API_URL_HERE',
{ contact, profilePicData } ...
And then capture it from my API as such:
router.post("/", upload.single('file'),(req, res) => {
console.log("REQ: "+ req);
console.log("BODY: " + JSON.stringify(req.body));
console.log("FILE: " + req.file);
The req.file is "undefined", i.e. null, and my req.body has a "profilePicData" key value pair which is empty. I assume this is because the entire form gets submitted as JSON and not as multipart form data.
But I can't google anything helpful around how to send both JSON and multipart to my API as one POST request so that both req.body and req.file pick up the right information. I guess understanding the theory and best practices behind what's going here is what I'm after. Should I have two POST urls, one for JSON and one for file? Or should I be submitting my JSON as multipart as well (how do I do that in Angular)? Any help is appreciated.
You will have to send everything as multipart by adding fields to an instance of FormData
and send it as the payload.
const form = new FormData();
form.append('file', profilePic);
form.append('contact', contact);
...
return this.http.post<ContactResponseData>('API_URL_HERE', form, ...)