DEV Community

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

Posted on • Edited on

4 2

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay