Home > Back-end >  How do I submit form and download the content without redirection?
How do I submit form and download the content without redirection?

Time:09-22

I am trying to create a form which downloads certain information upon submission via Flask. Here is a minimal working example.

app.py

from flask import Flask, render_template, request

app = Flask(__name__, template_folder='templates')

@app.route("/")
def home():
    return render_template('index.html')

@app.route("/download", methods=["GET"])
def download():
    return request.args

if __name__ == '__main__':
    app.run()

templates/index.html

<form method="get" action="download" id='download-form'>
  <select name="number">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <input type="submit">
</form>

By submitting the form, the user is redirected to /download with page content of {"number" : "1"}. How do I instead download this without being redirected to a new page?

With ajax I can do something like:

$('#download-form').on('submit', function(e) {
  e.preventDefault();
  $.ajax({
    type: 'GET',
    url: '/dwonload',
    data: $('#download-form').serialize(),
    success: function(data) {
      console.log(data); // how do I download this data?
    },
  });
});

But how do I then download the data (which is a string)?

CodePudding user response:

I'm using js fetch API, similar to AJAX. The response from the download URL will be passed to the hidden <a> tag and generate its attributes. Try something like this:

Controller

@app.route("/download/get", methods=["GET"])
def download():
    print(request.args)
    return request.args

Views (Template)

<body>
    <select name="number" id="number_select">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <button type="button" id="submit_btn" download>Submit</button>
    <hr>
    <div id="result"></div>

    <script>
        let select = document.querySelector('#number_select');
        let submitBtn = document.querySelector('#submit_btn');

        submitBtn.onclick = function() {
            let selectValue = select.options[select.selectedIndex].value;
            getResponse(selectValue)
        };

        function getResponse(val) {
            let url = '/download/get?number=' val '&count=10&name=naufal';

            fetch(url, {method: 'GET',})
            .then((response) => response.json())
            .then((data) => {
                let downloadBtn = document.createElement('a');

                downloadBtn.href = url;
                downloadBtn.target = '_blank';
                downloadBtn.download = 'response.json'
                downloadBtn.click()

                document.querySelector('#result').innerHTML = '<h1>This is the number: ' data.number;
            });
        }
    </script>
</body>

CodePudding user response:

The data can be downloaded as follows:

$('#download-form').on('submit', function(e) {
  e.preventDefault();
  $.ajax({
    type: 'GET',
    url: '/download',
    data: $('#download-form').serialize(),
    success: function() {
      var a = document.createElement('a');
      a.href = this.url;
      a.download = 'download.txt';
      document.body.append(a);
      a.click();
      a.remove();
    },
  });
});
  • Related