Search code examples
pythonajaxflaskrequestform-data

How to request several arguments from FormData?


This is a follow-up question from here: there I learned how to upload a file, process it and then populate the website again with its content using AJAX and FormData. For example, if I have a file data.csv like this:

A,B,C
1,3,4
2,4,2

I can pass it using AJAX and FormData

<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
    <div class="custom-file">
       <input id="myfile" name="myfile" type="file" class="custom-file-input">

       <label for="myfile" class="custom-file-label">
         Choose file...
       </label>
    </div>
</form>

// the javascript part
var form = $('#fileUploadForm')[0];
var formdata = new FormData(form);

$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "/_get_table",
        data: formdata,
        processData: false,
                contentType: false,
                cache: false,
                timeout: 600000,

and get:

enter image description here

I can then easily fetch this using

file = request.files['myfile']

and convert it into a dataframe using

df = pd.read_csv(file)

My question is now how I would do this, if I want to pass additional parameters (not only the file). Here it is suggested to use

var formdata = new FormData();
formdata.append("myform", form)
formdata.append("myvalue", 10)

which gives

enter image description here

and the headers

enter image description here

How do I now collect the info correctly? I can get myvalue like this

val = request.form['myvalue']

but I have not found a way to access and read myfile. If I e.g. try

file = request.files['myform'] 

I get

werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'myform'

I also tried other solutions from here but without success.


Solution

  • The problem is because you didn't add your file to the FormData correctly.

    As you are using multipart/form-data, your payload should be one file and some form-data. But in your screenshot, as you can see, you were adding one object.

    To solve this problem, actually you can directly add your value to the original FormData:

    var formdata = new FormData(form); 
    formdata.append("myvalue", 10);