Home > database >  How to download file and redirect user to another webpage using flask? [duplicate]
How to download file and redirect user to another webpage using flask? [duplicate]

Time:09-22

so I have been trying to make a website and I am encountering an issue here is my code

@app.route("/Download")
def download_final():
    lol = os.environ.get("hell")
    path = (f"Downloads/{lol}")
    return send_file(path, as_attachment=True)

@app.route('/remove')
def remove():
    os.remove("key.key")
    foo = os.environ.get("hell")
    os.remove(f"Downloads/{foo}")
    return render_template("remove.html") 

  • want to download file and then redirect user to another webpage where the user can agree and remove the file from server.

So I found this return send_from_directory() and redirect(url_for()) from here by using this method I am able to redirect but file is not being downloaded so then I noticed that when I redirect it remove those files so just to try this again I switched the path to homepage and started my website again I as getting the same issue redirect is working but file is not being downloaded

CodePudding user response:

In my opinion it is not possible with flask to serve a file and redirect in the same route.
If you want to send the file and then delete it, I recommend this answer.
If the user should give consent to delete the file, I suggest implementing it with javascript.

from flask import Flask
from flask import render_template, send_from_directory

app = Flask(__name__)

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

@app.route('/download')
def download():
    fname = 'example.jpg'
    return send_from_directory(app.static_folder, fname)

@app.route('/remove')
def remove():
    # remove file here!
    return render_template('remove.html')
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>

    <button id="download">Download</button>
    <script>
      (function() {

        const save = (data, filename) => {
          const elem = document.createElement('a');
          elem.href = URL.createObjectURL(data);
          elem.download = filename;
          elem.click();
        };

        const download = (url, callback) => {
          fetch(url)
            .then(res => res.blob())
            .then(data => {
              callback(data);
            });
        }

        const elem = document.querySelector('#download');
        elem.addEventListener('click', (evt) => {
          download('/download', (data) => {
            save(data, 'example.jpg');

            const shouldDeleteFile = confirm("Want to delete?");
            if (!shouldDeleteFile) return;
            
            location.href = '/remove';
          });
        });

      })();
    </script>

  </body>
</html>
  • Related