Serializing form data: text and file uploads

Hello. A have problem with form. When i send my form via fetch or AJAX, on server doesn’t download attached file.
This code doesn’ work:

 let testForm = document.querySelector(".project__form");
testForm.addEventListener('submit', e => {
        e.preventDefault();

        const formData = new FormData(testForm);
        fetch(testForm.getAttribute('action'), {
                method: 'POST',
                headers: {
                    'Accept': 'application/x-www-form-urlencoded;charset=UTF-8',
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: new URLSearchParams(formData).toString()
            })
            .then(function () {
                setTimeout(function () {
                    $(".success").text("Мы получили ваш запрос и свяжемся с вами в ближайшее время");
                }, 1000);

                setTimeout(function () {
                    $(".success ").fadeOut();
                }, 4000);
            });
    });

AJAX same doesn’t work for me:

 $(".project__form").submit(function (e) {
        e.preventDefault();
        var $form = $(this);
        $(".success").fadeIn(0);
        $.post(
            $form.attr("action"), $form.serialize()).then(function () {
            setTimeout(function () {
                $(".success").text("Мы получили ваш запрос и свяжемся с вами в ближайшее время");
            }, 1000);

            setTimeout(function () {
                $(".success ").fadeOut();
            }, 4000);
        });
    });

How a can solve my problem?

Niros,

can you tell us your netlify user name please? Also, when you say, “this code doesn’t work” what do you mean, exactly - does it not submit, or are you not receiving form results in your dashboard?

Also, this post might be helpful for some basic debugging:

andrewlymar
andriilymar@gmail.com

I mean i recive form result only from < input type="text>, but from < input type="file> i recive empty field. I have this problem only when i use ajax or fetch, if i use defuault succes page, all ok.

Hi again,

There can be a couple of reasons why this is occurring - file uploads should definitely be possible.

If I were you, I would go through a few of the code examples by people who have posted about file uploads here in the forums, and take a look at their code:

https://community.netlify.com/search?q=file%20upload

If that still doesn’t help, let us know what you have tried and we will take another look.

Hiya @Niros, I also wanted to share a post where someone else was running into similar issues in case it’s helpful for you:


Let us know if this fixes things for you or if we can answer any other questions