0

i have this code for upload file to flask.

client side:

<form id="upload-file" method="post" enctype="multipart/form-data">
    <fieldset>
        <label for="file">Select a file</label>
        <input name="file8" type="file">
    </fieldset>
    <fieldset>
        <button id="upload-file-btn" type="button">Upload</button>
    </fieldset>
</form>
<script>
  $(function() {
    $('#upload-file-btn').click(function() {
        var form_data = new FormData($('#upload-file')[0]);
        $.ajax({
            type: 'POST',
            url: '/uploading',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            success: function(data) {
                console.log('Success!');
            },
        });
    });
});

</script>

server side:

@app.route('/uploading', methods = ['POST'])
def uploading():
    if request.method == 'POST':
        file = request.files['file8']
        if file and a

this code upload file and work. How can i send more info to flask same time ?like time = 2020 , age=20 , ...

i find my answer but i cant answer to my question, so i write my ans here:


i use header,send more info like id , ... with user (but this is unsafe):

client side:

<script>
$(function() {
    $('#upload-file-btn').click(function() {
        var form_data = new FormData($('#upload-file')[0]);
        form_data.append('username', 'Chris');
         //form_data.append ('id',$('#upload-file')[0]);

        console.log(form_data);
        $.ajax({
            type: 'POST',
            url: '/uploading',
            data: form_data, headers: {
      'Id': 2528,'age':20
    },
            contentType: false,
            cache: false,
            processData: false,
            success: function(data) {
                console.log('Success!');
            },
        });
    });
});

</script>

server side:

@app.route('/uploading', methods = ['POST'])
def uploading():
    if request.method == 'POST':
        file = request.files['file8']
        id=request.headers['Id']
        age=request.headers['age']
henrry
  • 268
  • 2
  • 12

1 Answers1

0

Put the data in the form, then pass the form to new FormData instead of just the file input.

e.g.

<form id="upload-file" method="post" enctype="multipart/form-data">
    <fieldset>
        <label for="file">Select a file</label>
        <input name="file8" type="file">
    </fieldset>
    <fieldset>
        <button id="upload-file-btn">Upload</button>
    </fieldset>

    <input type=hidden name=time value=2020>
    <input type=hidden name=age value=20>

</form>

and

$("form").on("submit", function (e) {
    e.preventDefault();
    const form = this;
    const form_data = new FormData(form);
    // etc
});
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205