DEV Community

Cover image for How to create server files with Flask
Nelson Adonis Hernández
Nelson Adonis Hernández

Posted on • Updated on

How to create server files with Flask

In this example I will show you how to upload, download, delete and obtain files with Flask

Upload multiple files with Form Data


from flask import Flask
import os

app = Flask(__name__)

@app.route("/upload", methods=['POST'])
def upload_image():
    if request.method == "POST":
        file = request.files['file']
        try:
            file.save(os.getcwd() + "/images/" + file.filename)
            return "Imagen saved"
        except FileNotFoundError:
            return "Folder not found"

if __name__ == '__main__':
    app.run(debug=True, port=8000, host="0.0.0.0")
Enter fullscreen mode Exit fullscreen mode

Download files


from flask import Flask
import os

app = Flask(__name__)

@app.route('/download/file/<string:filename>')
def download_image(filename):
    return send_from_directory(os.getcwd() + "/images/", path=filename, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True, port=8000, host="0.0.0.0")
Enter fullscreen mode Exit fullscreen mode

Get files


from flask import Flask
import os

app = Flask(__name__)

@app.route('/file/<string:filename>')
def get_image(filename):
    return send_from_directory(os.getcwd() + "/images/", path=filename, as_attachment=False)

if __name__ == '__main__':
    app.run(debug=True, port=8000, host="0.0.0.0")
Enter fullscreen mode Exit fullscreen mode

Delete files


from flask import Flask
import os

app = Flask(__name__)

@app.route('/delete', methods=['POST'])
def remove_image():
    filename = request.form['filename']

    # CHECK IF EXISTS FILE
    if os.path.isfile(os.getcwd() + "/images/" + filename) == False:
        return "Esto no es un archivo"
    else:
        try:
            os.remove(os.getcwd() + "/images/" + filename)
        except OSError:
            return "Error :(("
        return "File deleted"

if __name__ == '__main__':
    app.run(debug=True, port=8000, host="0.0.0.0")
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Some comments have been hidden by the post's author - find out more