pycloudinary icon indicating copy to clipboard operation
pycloudinary copied to clipboard

Add a feature whereby users can validate file size before being uploaded.

Open aayobam opened this issue 7 months ago • 3 comments

Feature request for Cloudinary Python SDK

Add a feature whereby users can validate file size before being uploaded.

Explain your use case

I want the cloudinary python sdk team to ensure that users can check or validate the filesize of a file before being uploaded just like in native django file upload without cloudinaryfile field.

Describe the problem you’re trying to solve

I am a backend web developer and i use python and django a lot. for backend web development. Initially in a django project when uploading a file, one could determine or validate the file size(bytes, kb, mb, gb) before it's being uploaded to the database . But recently i tried achieve that with CloudinaryField and i got the error that the file field doesnt have attribute "file.size". A typical django file upload validation without the use of CloudinaryField looks like the below code.

import mimetypes
from django.db import models
from django.core.exceptions import ValidationError
from django.core.files.storage import FileSystemStorage

def file_validation(file):
    FILE_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 1  # 1mb
    file_types = ["image/png", "image/jpeg", "image/jpg", "application/pdf"]

    if not file:
        raise ValidationError("No file selected.")

    if file.size > FILE_UPLOAD_MAX_MEMORY_SIZE:
        raise ValidationError("File shouldn't be larger than 1MB.")

    fs = FileSystemStorage()
    filename = fs.save(file.name, file)
    file_type = mimetypes.guess_type(filename)[0]
    if file_type not in file_types:
        raise ValidationError(
            "Invalid file, please upload a clearer image or pdf file that shows your full name, picture and date of birth.")

class UploadFile(models):
    document = models.FileField(upload_to="media", validators=[file_validation])
    profile_picture = models.FileField(upload_to="media", validators=[file_validation], blank=True, null=True)

The above code works well but when CloudinaryField is been used, file size validation doesn't work since "size" attribute doesn't exist. I'll want this to be added and enabled to make file upload validation to cloudinary possible and seamless.

Do you have a proposed solution?

I do not have code sample to achieve this, which is why i'm suggesting this to the developers of cloudinary python sdk to resolve this or add such feature.

aayobam avatar Dec 06 '23 12:12 aayobam