zape
zape

Reputation: 115

Flask request.files returns ImmutableMultiDict([])

I have tried a million times to get this working. I am making a web app and I have a button (modal) that pops up where the user enters the name and uploads a file. When the user clicks on Save Well. The request.files returns ImmutableMultiDict([])

This is the button:

Button add new well

Code for the modal on the web page:

  $(document).ready(function(){
	$('#SaveNewWellButton').on('click', function(e){
		
    e.preventDefault()
    $.ajax({
		url:'./createNewWellfolder',
        type:'post',
        data:{'newWellNameImported':$("#newWellNameImported").val(), 
		      'WTTcsvfile':$("#WTTcsvfile").val()
		},
		success: function(data){
				//$("#result").text(data.result)
				$('#selectWell').html(data)
				alert( "New well created" );
			},
			error: function(error){
				console.log(error);
			}
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span class="table-add float-right mb-3 mr-2" data-toggle="modal" data-target="#myModal"> 
  <button type="submit" class="btn btn-success">Add New Well</button></span>
  <!-- The Modal -->
  <div class="modal fade" id="myModal">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
      
        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Import CSV file:</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        
        <!-- Modal body -->
		<form action="/createNewWellfolder" method="post" enctype="multipart/form-data">
        <div class="modal-body">
          Name of well:<input type="text" id="newWellNameImported" class="form-control"></input>
        </div>
        
        <!-- Modal footer -->
        <div class="modal-footer">
		<input type="file" name="csvfile" value ="csvfile" id="csvfile">
		</br>
		  <button type="submit" class="btn btn-primary" id="SaveNewWellButton">Save Well</button>
          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
        </div>
		 </form>
        
      </div>
    </div>
  </div>

The python code looks like this:

@app.route('/createNewWellfolder', methods=['GET', 'POST'])
def createNewWellfolder():
    print('request.method : %s',  request.method)
    print('request.files : %s', request.files)
    print('request.args : %s', request.args)
    print('request.form : %s', request.form)
    print('request.values : %s', request.values)

Output from terminal:

    request.method : %s POST
    request.files : %s ImmutableMultiDict([])
    request.args : %s ImmutableMultiDict([])
    request.form : %s ImmutableMultiDict([('newWellNameImported', 'Sample Well 14')])
    request.values : %s CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([('newWellNameImported', 'Sample Well 14')])])

Just want to add that the below code works. But how can I get it to work on my larger web app? I guess it has something to do with app.route. But I have tried so many things, like adding it to the action form with url_for etc. Nothing seems to work.

import os
from flask import Flask, flash, send_from_directory, request, redirect, url_for
from werkzeug.utils import secure_filename
from os.path import dirname, join

DATA_DIR = join(dirname(__file__), 'data/')
wellNames = next(os.walk('data'))[1]

print(DATA_DIR, wellNames[0])

UPLOAD_FOLDER = DATA_DIR + wellNames[0] + '/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'csv', 'docx'])

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

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

    if request.method == 'POST':
        print('------------->', request.files)
    # check if the post request has the file part
        if 'csvfile' not in request.files:
            flash('No file part')
        file = request.files['csvfile']
        print('------------->', file)

        if file.filename == '':
            flash('No selected file')
        if file and allowed_file(file.filename):
            print('hello im here------------->', file)
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

    return '''
    <!-- Modal body -->
    <form method=post enctype=multipart/form-data>
    <div class="modal-body">
      Name of well:<input type="text" id="newWellNameImported" class="form-control"></input>
    </div>

    <!-- Modal footer -->
    <div class="modal-footer">
    <input type=file name="csvfile" id="csvfile" >
    </br>
      <button type="submit" class="btn btn-primary" id="SaveNewWellButton" >Save Well</button>
      <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
    </div>
     </form>
     '''    
   if __name__ == '__main__':
        print('Opening single process Flask app with embedded Bokeh application on http://localhost:8000/')
        app.secret_key = 'secret key'
        app.debug = True
        app.run(port = 8000)

Output from terminal:

-------------> ImmutableMultiDict([('csvfile', <FileStorage: 'testcsv.csv' ('application/vnd.ms-excel')>)])
-------------> <FileStorage: 'testcsv.csv' ('application/vnd.ms-excel')>
hello im here-------------> <FileStorage: 'testcsv.csv' ('application/vnd.ms-excel')>

Upvotes: 0

Views: 9857

Answers (2)

dennisdee
dennisdee

Reputation: 160

Would you mind elaborating on the issue a bit more? It's expected that Flask Request returns an ImmutableMultiDict:

MultiDict object containing all uploaded files. Each key in files is the name from the <input type="file" name="">. Each value in files is a Werkzeug FileStorage object.

It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem.

Note that files will only contain data if the request method was POST, PUT or PATCH and the <form> that posted to the request had enctype="multipart/form-data". It will be empty otherwise.

See the MultiDict / FileStorage documentation for more details about the used data structure.

http://flask.pocoo.org/docs/1.0/api/#flask.Request.files

Upvotes: 2

Julian Camilleri
Julian Camilleri

Reputation: 3125

I believe the problem is with your serialisation of the form. - Try giving this a read.

You can also use something similar to the below:

(function($) {
  $.fn.serializeFiles = function() {
    var form = $(this),
        formData = new FormData(),
        formParams = form.serializeArray();

    $.each(form.find('input[type="file"]'), function(i, tag) {
      $.each($(tag)[0].files, function(i, file) {
        formData.append(tag.name, file);
      });
    });

    $.each(formParams, function(i, val) {
      formData.append(val.name, val.value);
    });

    return formData;
  };
})(jQuery);

You can eliminate which part is not working by not preventing the form to submit, and see if by default; the form submits files' to the backend. - It's highly unlikely that you're passing the correct data from the way you're serialising the form.

Upvotes: 0

Related Questions