Created
May 14, 2022 05:42
-
-
Save kundlatsch/c755b63df35767dc314e2ea110113a8a to your computer and use it in GitHub Desktop.
How to upload files to a Flask REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from flask import Flask, flash, request, redirect, url_for | |
from flask_restful import Resource, Api | |
from werkzeug.utils import secure_filename | |
UPLOAD_FOLDER = 'files' | |
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} | |
app = Flask(__name__) | |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER | |
api = Api(app) | |
class FileHandler(Resource): | |
def allowed_file(self, filename): | |
return '.' in filename and \ | |
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | |
def post(self): | |
# Get Text type fields | |
form = request.form.to_dict() | |
print(form) | |
if 'file' not in request.files: | |
return 'No file part' | |
file = request.files.get("file") | |
if file and self.allowed_file(file.filename): | |
filename = secure_filename(file.filename) | |
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) | |
return 'File uploaded successfully' | |
api.add_resource(FileHandler, "/") | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment