0

I want to create Bootstrap Modal that has a form with textarea and image, and send that to the server.

My form on modal looks like this:

<form id="formData" method="POST" enctype="multipart/form-data">
    <fieldset class="form-group">
        <div class="form-group">
            <textarea class="form-control" id="content" name="content" required></textarea>
        </div>
        <div class="form-group">
            <label for="image">Got any photo?</label>
            <input class="form-control-file" id="image" name="image" type="file">
        </div>
    </fieldset>
    <button class="btn purple-btn-outline-modal" type="submit">Add</button>
</form>

The AJAX I'm using:

var form = document.forms.namedItem("formData");
form.addEventListener('submit', function (ev) {
    var oData = new FormData(form);
    oData.append('image', $('#image')[0].files[0])
    for (var p of oData) {
        console.log(p); // <- logs image in oData correctly
    }
    $.ajax({
        url: '/test/',
        type: 'POST',
        method: 'POST',
        data: oData,
        enctype: 'multipart/form-data',
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
        },
    });
    ev.preventDefault();
}, false);

But on the server side (Python Flask) the image is not in request form:

@main.route('/test/', methods=['POST'])
def test():
    if request.method == 'POST':
        app.logger.debug(request.form)            # ImmutableMultiDict([('content', 'my sent content')])
        app.logger.debug(request.form['content']) # 'my sent content'
        app.logger.debug(request.form['image'])   # <- KeyError: 'image'
    return jsonify(...)

What is wrong?

ofca1234
  • 53
  • 7

1 Answers1

0

SOLVED.

Solution by @v25:

request.files['image']

worked.

ofca1234
  • 53
  • 7
  • 1
    Nice one! See another [answer I wrote](https://stackoverflow.com/a/58934639/2052575) which has more info on what this `request.files` object actually is, and its attributes. Of course, in your example the key is `image`, as specified on the fourth line of your JS example. – v25 Mar 28 '20 at 10:18