Search code examples
javascriptnode.jsmultipartform-datamulterform-data

How to submit a multipart image - Error: Multipart: Boundary not found


I have a client side javascript sdk that submits an image to a server side node.js api that uses the multer library to parse the image.

However ive noticed if i set a header to be content-type multipart-formdata multer will throw an error saying

Error: Multipart: Boundary not found

async submitDocument(id, side, image) {

        const url = this.API_URL + "/api/document";

        let formData = new FormData();
        formData.set("image", image, "front.jpg");
        formData.set("side", side);

        let headers = new Headers();
        headers.set("content-type", "multipart/form-data");
        headers.set("Authorization", "Bearer " + this.API_KEY);

        const request = {
            method: "POST",
            body: formData,
            headers: headers,
        };

        try {

            const response = await fetch(url, request);
            const data = await response.json();

            return data;

        } catch (err) {
            throw err;
        }

    }

Solution

  • As the error message says, a multipart/form-data content-type requires a boundary parameter.

    Don't set the Content-Type yourself. Allow the browser to generate it from the formData object.