3
How to create server files with Flask
source link: https://dev.to/nelsoncode/how-to-create-server-files-with-flask-4hdp
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
In this example I will show you how to upload, download, delete and obtain files with Flask
How to upload multiple files by Form Data using Flask
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 modeExit fullscreen mode
How to download files using Flask
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 modeExit fullscreen mode
How to get files using Flask
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 modeExit fullscreen mode
How to delete files using Flask with Form Data
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 modeExit fullscreen mode
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK