To create a separate interface for uploading and downloading images, you’ll follow similar steps as for videos, but you’ll handle different file extensions and use different routes.
-
Firstly, adjust the configuration in your init.py:
app.config['ALLOWED_IMAGE_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}
-
Now create a new Model in models.py for images:
class Image(db.Model): id = db.Column(db.Integer, primary_key=True) filename = db.Column(db.String(120), unique=True, nullable=False) original_filename = db.Column(db.String(120), unique=True, nullable=False) def __init__(self, filename, original_filename): self.filename = filename self.original_filename = original_filename
-
You should also create a new Resource for uploading images:
class ImageUpload(Resource): def post(self): if 'image' not in request.files: return {"error": "No image file provided"}, 400 image = request.files['image'] allowed_extensions = current_app.config['ALLOWED_IMAGE_EXTENSIONS'] if not allowed_file(image.filename, allowed_extensions): return {"error": "Invalid file extension"}, 400 original_filename = image.filename secure_name = secure_filename(original_filename) image.save(os.path.join(current_app.config['UPLOAD_FOLDER'], secure_name)) new_image = Image(filename=secure_name, original_filename=original_filename) sqlite_db.session.add(new_image) sqlite_db.session.commit() return {"message": "Image uploaded and saved successfully", "id": new_image.id}, 201
-
And another Resource for getting images:
class ImageResource(Resource): def get(self, image_id): image = Image.query.get(image_id) if image is None: return {"error": "Image not found"}, 404 return send_from_directory(current_app.config['UPLOAD_FOLDER'], image.filename)
-
Finally, register these new resources with Flask-Restful in your API:
api.add_resource(ImageUpload, '/images/upload') api.add_resource(ImageResource, '/images/<int:image_id>')
This way, you can use /images/upload for image upload and /images/int:image_id for image download without interfering with the video module. Just make sure that the folder specified in app.config[‘UPLOAD_FOLDER’] is writable and is properly configured to store the uploaded files.