Skip to content
Advertisement

how do I post form data and upload file with the JS fetch API

I am trying to post form data using JS fetch API, also i successfully send data and get response , but got an error in file uploaded my file is not uploaded , and also not get stored filename into database.

<form id="signup">
    <label for="myName">Send me your name:</label>
    <input type="text" id="myName" name="name" value="abc">
    <br>
    <label for="userId">your id:</label>
    <input type="text" id="userId" name="id" value="123">
    <br>
    <label for="pic">your photo:</label>
    <input id="profile" name="profile" id="profile" type="file">
    <br>
    <input id="postSubmit" type="submit" value="Send Me!">
</form>

And javascript code

const thisForm = document.getElementById('signup');
    const profile = document.getElementById('profile');
    thisForm.addEventListener('submit', async function (e) {
    e.preventDefault();
    const formData = new FormData(thisForm).entries()
    formdata.append("profile",profile.files[0]);
        const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
            method: 'POST',
            headers: { 'Content-Type': 'multipart/form-data' },
            body: JSON.stringify(Object.fromEntries(formData))
        });

        const result = await response.json();
        console.log(result);

Advertisement

Answer

No need to transform to JSON, and no need to use entries() on FormData. Also check the spelling, you wrote formdata which is different than formData.

const thisForm = document.getElementById('signup');
var formData = new FormData(thisForm);
const profile = document.getElementById('profile');
formData.append("profile", profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
  method: 'POST',
  headers: { 'Content-Type': 'multipart/form-data' },
  body: formData
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement