Taiosquare
Taiosquare

Reputation: 45

Sending an image uploaded in a form to a server using formdata and fetchAPI in JS

I am trying to extract image and text data from a single form. I tried using formdata.get('image') to get the image selected by a user, but it's not working as I am receiving an undefined value on my server. I would like to know the appropriate way to get the image selected by a user in the form using formdata or any other method, thanks.

The Form

 <form id = "register" class = "edit-note" enctype = "multipart/form-data">
                <div>
                    <label>Heading:</label>
                    <input type = "text" name = "heading" placeholder = "<%= Note[0].heading %>" id = "heading">
                </div>
                <div>
                    <label>Small Text:</label>  
                    <input type = "text" name = "stext" placeholder = "<%= Note[0].smallText %>" id = "stext">
                </div>

                <div>
                    <label>Featured Image:</label>
                    <img src = "<%= Note[0].image %>" height = "110px" width = "132px">
                    <input type = "file" name = "image" id = "fimage">
                </div>
                <div>
                    <label>Background Image:</label>
                    <img src = "<%= Note[0].background %>" height = "110px" width = "132px">
                    <input type = "file" name = "bimage" id = "bimage">
                </div>
    
                <div>
                    <label>Content:</label> 
                    <textarea name = "content" placeholder = "<%= Note[0].content %>" id = "content"></textarea>
                </div>

                <input type = "submit" name = "register" value = "Save Changes">
            </form>

The FetchAPI

const noteForm = document.querySelector('.edit-note');

noteForm.addEventListener('submit', function(e) {
    e.preventDefault();
    let url = "";

    const formData = new FormData(this);

    fetch( '/images', {
        method: 'POST',
        body: formData.get('image')
    }).then(response => {
        response.json();
    }).then(URL => {
        //console.log(URL);
        url = URL;

I excluded parts of the FetchAPI not relevant to the question.

Upvotes: 1

Views: 16092

Answers (1)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26268

If you want to upload a file using XMLHttpRequest then you have to use FormData, which you are doing, but not in a right way.

Step I: Create a FormData instance

let formData = new FormData();

Step - II: Append the data in it

formData.append('file_to_upload', fileField.files[0]);  // Here fileField is the input file reference

Step III: Send formData over XMLHttpRequest and you will get the file with name that you have provided it while appending it in the formData, in above case it is - file_to_upload

Upvotes: 6

Related Questions