Implement the module for uploading and downloading images simultaneously

  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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值