/File-Upload-with-Flask-HTMX-progress-bar

File Upload Flask App with HTMX progress bar

Primary LanguagePythonMIT LicenseMIT

License: MIT Python

File Upload web app with Flask and HTMX progress bar

  • In this example, file upload with submit button via ajax, along with a progress bar. This implementation with JavaScript using some utility methods in htmx.

  • Here is the steps to implement htmx into a typical file upload web app
  1. install htmx library
  • In order to have htmx support for your website, we need to install htmx library on to your web server, so that allows you to access modern browser features directly from HTML. donwload htmx.min.js via unpkg.com. Htmx is a dependency-free, browser-oriented javascript library. This means that using it is as simple as adding a <script> tag to your document head. No need for complicated build steps or systems.

Code snippet:

            <script src="/static/js/htmx.min.js"></script>
  1. Add htmx tag into html form tag as attribute. all htmx comes with hx prefix.
    Code snippet:
            <form id="my-form"  
                        hx-encoding="multipart/form-data"
                        hx-post="/uploads"
                        hx-target="#list_results"
                        hx-on::after-request="if(event.detail.successful) this.reset()"
            >
  • We have a form of type multipart/form-data so that the file will be properly encoded with hx-enconding attribute, replacing normal html enctype attibute.
  • We post the form to /uploads with hx-post, send form data to target URL.
  • we forward the response output to target div id "#list_results" with hx-target attibute.
  • we ensure a form reset only after a successful event with if(event.detail.successful) this.reset()
  • We have a progress element to show the file upload progress with id my-progress.
            <progress id="my-progress" value="0" max="100"></progress>
  • We listen for the htmx:xhr:progress event refer back to id my-progress and update the value attribute of the progress bar based on the loaded and total properties in the event detail.
    JavaScript Code snippet:
            <script>
                htmx.on('#my-form', 'htmx:xhr:progress', function(evt) {
                  htmx.find('#my-progress').setAttribute('value', evt.detail.loaded/evt.detail.total * 100)
                });
            </script>

Here is the Snippet Code view in full:
full-code-snippet

See File Upload Progress Bar in action:

Watch the video

Summary:

This is a File Upload Web app running with Flask + Python. Implemented with htmx progress bar to improve user experience.

Features

  • Serve static files
  • Upload/Download files
  • Schedule file removal after certain days
  • Support https