AJAX file Upload with Vanilla JavaScript and python flask (WithOUT jQuery)

In the aritcle How to upload multiple files with python flask, we showed how to upload with html form.

In this aritcle, we will show how to upload in the AJAX way.

Frontend html

Aussume that the url /upload handles uploading.

<form id="file-form" method="post" enctype="multipart/form-data">
    <input id="file" type="file" name="file"/>
    <input type="submit"/>

  var fileForm = document.getElementById('file-form');
  fileForm.addEventListener('submit', function (event) {

    var xhr = new XMLHttpRequest();
    xhr.open('post', '/upload', true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4 && xhr.status == 200) {

    var formData = new FormData(fileForm);

Things you should notice about the html form above:

  • enctype attribute of the html form must be multipart/form-data.
  • new FormData(fileForm) builds the AJAX post data from the html form.

Backend flask

import os
from flask import request, redirect
from werkzeug.utils import secure_filename

@app.route('/upload', methods=('POST',))
def upload():
    file = request.files['file']
    fn = secure_filename(file.filename)
    file.save(os.path.join(FILES_DIR, fn))  # replace FILES_DIR with your own directory
    return 'ok'  # change to your own logic

Things you should notice about the flask code above:

  • methods must include POST
  • use secure_filename to prevent malicious file name.

Drag and Drop to upload

Please refer to Upload multiple files using "drag and drop" with html5 and flask.

Posted on 2022-09-23