1

I'm creating a simple web app with Flask, and I want users to be able to save (or export) a file (example csv file) to a location of their choice. Preferably, a "save as" dialog box should pop up. I was hoping there's a way to simply do this from backend with flask. But any simple way will be nice.

Please how do I implement this? Thanks

davidism
  • 121,510
  • 29
  • 395
  • 339
Able
  • 49
  • 4

1 Answers1

0

Normally if we are using a save as feature this can means that you want to upload the file on the server (which in dev environment case is localhost). For this soul purpose we have some functionalities in Flask already.

For starters you have to setup the flask app and two routes, one for getting the filepath and then the second for getting the file and uploading it.

from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)

@app.route('/upload')
def upload_file():
   return render_template('upload.html')
    
@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']
      f.save(secure_filename(f.filename))
      return 'file uploaded successfully'

This will be your upload.html file:

<html>
   <body>
      <form action = "http://localhost:5000/uploader" method = "POST" 
         enctype = "multipart/form-data">
         <input type = "file" name = "file" />
         <input type = "submit"/>
      </form>   
   </body>
</html>

The default upload folder path and maximum size of uploaded files can be defined in the configuration settings for the Flask object.

Define the path to the upload folder

app.config['UPLOAD_FOLDER']

I believe this is what you were looking for.

mtiTayyab
  • 11
  • 3
  • You can also use the below issue if you want to do the opposite and develop something for downloading a file: https://stackoverflow.com/questions/24577349/flask-download-a-file – mtiTayyab May 03 '21 at 00:17