JackJones's avatar

Is there a way to upload files without using the FormData object?

I am having to loop through my user object and append it to form data just so I can append an image, is there a way to send a file without using FormData?

0 likes
1 reply
jlrdw's avatar

I do this if just one file:

    buttonForm.addEventListener("click", async (event) => {

       event.preventDefault();
       const thisForm = document.getElementById('personal');
        var formData = new FormData(thisForm);
        var url = '<?php echo DIR . "personal/add"; ?>';
        const response = await
                fetch(url, {
                    method: 'POST',
                    body: formData
                });
        if (response.status === 200) {
            response.text().then(function (text) {
                //handle your response
            });

        } else {
            console.log("error"); // handle as needed
        }
    });

Without appending. Never had to loop.

Edit another with axios js:

    buttonForm.addEventListener("click", async (event) => {
        event.preventDefault();
        const thisForm = document.getElementById('personal');
        var formData = new FormData(thisForm);
        var url = '<?php echo DIR . "personal/add"; ?>';

        axios({
            method: "post",
            url: url,
            data: formData,
            //headers: axios figures it out, not needed
        })
                .then(function (response) {
                    if (response.status === 200) {
                        // handle response
                    }
                    console.log(response);
                })
                .catch(function (response) {
                    //handle error
                    console.log(response);
                });

    });

Works the exact same.

Please or to participate in this conversation.