Skip to content
Advertisement

How to upload a (csv) file with an AJAX call and Flask

I’m updating on updating an older project that uses AJAX and have decided to use Flask to do so. For the particular page I’m currently working on, I need to be able to upload a CSV and read the data in the file (no need to save it). I have several other pages that work using AJAX, but they return form data back to Flask (e.g. what semester it is, what year it is, etc). Ideally, I’d like to be able to upload the CSV and read the form data (the variables I have called formData and myFormData below).

I have found this post and based my MWE on it, but when I look at request.files, I get an empty dictionary. Here is the code I have:

run.py:

JavaScript

__init__.py:

JavaScript

file_upload.py:

JavaScript

fileUpload.html:

JavaScript

fileUpload.js:

JavaScript

A little additional info: This is part of a larger project which is why I’m using Blueprints and flask_excel. I’ve seen folks recommend using something other than AJAX, but I’m trying to make the pages run with python3 by using Flask without rewriting everything that’s already there.

Advertisement

Answer

So that the form can be serialized, it is necessary for the input fields to have a name attribute.
I’m using the form’s submit event in the following minimal example. The event listener is registered when the document is fully loaded. When the form is submitted, the form data is serialized and sent via ajax.

JavaScript

The server-side code remains essentially the same. However, I advise you, for reasons of cleanliness, to separate endpoints for ajax requests from those that return html.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement