1

I have a form with multipart/form-data enctype, something like this HTML code:

<form id="myform" action="/parse" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name" id="name" placeholder="Enter your name">
Age: <input type="number" name="age" id="age" placeholder="Enter your age">
Photo: <input type="file" name="image" id="image">
<input type="submit">
</form>
<div id="preview"></div>

Now I can show the preview image with this jQuery code:

$('#image').change(function() {
    var file = $(this).get(0).files[0];
    //var preview = $('#preview');
    var img = document.createElement('img');
    img.src = window.URL.createObjectURL(file);
    $('#preview').html(img);
    var reader = new FileReader();
    reader.onload = function(e) {
        window.URL.revokeObjectURL(this.src);
    }
    reader.readAsDataURL(file);
    $('#preview img').css({'width':'200px'});
});

... and I have this FormData() object:

var data = new FormData();
data.append('name', $('#name').val());
data.append('age', $('#age').val());

How can I add the image's datas to the FormData() object?

Thanks!

1 Answer 1

1

This will automatically add all the fields of your form to the FormData object, including the file input.

var data = new FormData($('#myform')[0]);

You don't need to use

data.append('name', $('#name').val());
data.append('age', $('#age').val());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.