Search code examples
javascriptform-data

Having problems with formdata.append()


I'm trying to upload file with form data. So I append image data to formdata object. But I keep getting error: The laptop image field is required. (Spelling of 'laptop_image' is correct).

I also had to append some other data and they worked just fine

const fileInput = document.getElementById('laptop_image');

async function handleFormSubmit(event) {
    event.preventDefault();
    const form = document.querySelector('form');
    const url = form.action;

    try {
        const formData = new FormData(form);
        formData.append('laptop_image', fileInput.files[0]);

        const responseData = await postFormDataAsJson({ url, formData});
        console.log({ responseData });
    } catch (error) {
//also console.log(fileInput.files[0]); logs an image object
        console.error(error);
    }
}

form.addEventListener("submit", handleFormSubmit);


What am I doing wrong? :/


Solution

  • You haven't provided postFormDataAsJson, but we can make some assumptions about what it does.

    You can't easily serialise a FormData object to JSON. JSON.stringify will convert it to an empty object.

    const fd = new FormData();
    fd.append("key", "value");
    const json = JSON.stringify(fd);
    console.log(`JSON: ${json}`);

    While there are ways to loop through the data in a FormData object to produce JSON from it:

    • This largely renders using a FormData object pointless
    • JSON still doesn't have a "File" data type

    Generally, if you want to upload files + other data, you need to send multipart form data. The Ajax APIs built into browsers will serialise FormData objects to that format automatically.

    fetch(url, { method: "POST", body: fd });
    

    Of course, you need to send data in a format that the HTTP server is expecting (and we don't know anything about the one you are posting the data to).