Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading file with multer (NodeJS) + other form data on same POST request (Angular)

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.

like image 423
glog Avatar asked Sep 13 '26 04:09

glog


1 Answers

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, ...)
like image 60
thammada.ts Avatar answered Sep 14 '26 18:09

thammada.ts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!