Home > Software engineering >  Can't get image upload to work with Flask and JQuery
Can't get image upload to work with Flask and JQuery

Time:10-30

The following code allows you to submit forms and return a variation of the text from Flask using AJAX and JQuery:

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('form.html')

@app.route('/process', methods=['POST'])
def process():

    email = request.form['email']
    name = request.form['name']

    if name and email:
        newName = name[::-1]

        return jsonify({'name' : newName})

    return jsonify({'error' : 'Missing data!'})

if __name__ == '__main__':
    app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
    <title>AJAX Example</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

    <script src="{{ url_for('static', filename='js/form.js') }}"></script>
</head>
<body>
<div class="container">
    <br><br><br><br>
    <form class="form-inline">
      <div class="form-group">
        <label class="sr-only" for="emailInput">Email address</label>
        <input type="email" class="form-control" id="emailInput" placeholder="Email">
      </div>
      <div class="form-group">
        <label class="sr-only" for="nameInput">Name</label>
        <input type="text" class="form-control" id="nameInput" placeholder="First Name">
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
    <br>
    <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
    <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
</body>
</html>
$(document).ready(function() {

    $('form').on('submit', function(event) {

        $.ajax({
            data : {
                name : $('#nameInput').val(),
                email : $('#emailInput').val()
            },
            type : 'POST',
            url : '/process'
        })
        .done(function(data) {

            if (data.error) {
                $('#errorAlert').text(data.error).show();
                $('#successAlert').hide();
            }
            else {
                $('#successAlert').text(data.name).show();
                $('#errorAlert').hide();
            }

        });

        event.preventDefault();

    });

});

But when I slightly modify the code to do the same thing with a uploaded file's name it doesn't work. All I have done is changed the type of form so that it takes in files and then made it so that it reverses the filename rather than the inputted text from the previous version. Do you know what I am doing wrong here?

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('form.html')

@app.route('/process', methods=['POST'])
def process():

    filename = request.files['file'].filename

    if filename:
        newName = filename[::-1]

        return jsonify({'name' : newName})

    return jsonify({'error' : 'Missing data!'})

if __name__ == '__main__':
    app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
    <title>AJAX Example</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

    <script src="{{ url_for('static', filename='js/form.js') }}"></script>
</head>
<body>
<div class="container">
    <br><br><br><br>
    <form method="POST" action='/process' enctype="multipart/form-data">
        <div>
          <label for="file">Choose file to upload</label>
          <input type="file" id="file" name="file">
        </div>
        <div>
          <button type="submit" class="btn btn-default">Submit</button>
        </div>
       </form>
    <br>
    <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
    <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
</body>
</html>
$(document).ready(function() {

    $('form').on('submit', function(event) {

        $.ajax({
            data : {
                
                file : $('#file')
            },
            type : 'POST',
            url : '/process'
        })
        .done(function(data) {

            if (data.error) {
                $('#errorAlert').text(data.error).show();
                $('#successAlert').hide();
            }
            else {
                $('#successAlert').text(data.name).show();
                $('#errorAlert').hide();
            }

        });

        event.preventDefault();

    });

});

CodePudding user response:

If you use an object of the type FormData to serialize and transfer the data of the form it should work.

$(document).ready(function() {
  $('form').submit(function(event) {
    let formData = new FormData(event.target);
    $.ajax({
      data: formData,
      type : 'POST',
      url : '/process',
      contentType: false,
      processData: false
    })
    .done(function(data) {
      if (data.error) {
        $('#errorAlert').text(data.error).show();
        $('#successAlert').hide();
      } else {
        $('#successAlert').text(data.name).show();
        $('#errorAlert').hide();
      }
    });
    event.preventDefault();
  });
});
  • Related