Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid Overwriting files when uploading with django-ckeditor to ftp server -> possible fix #1360

Open
HerrEich opened this issue Mar 4, 2024 · 2 comments

Comments

@HerrEich
Copy link

HerrEich commented Mar 4, 2024

Hi,

files that are uploaded in the django-ckeditor5 to a ftp server are overwritten if they share the same name. i added some code to fix this. i just wanted to leave this here in case anyone else has the same problem. i am just an amateur and not really experienced with this whole "pull request" stuff.

So here is a possible fix:

I changed the original _put_file function in ftp.py to:

from django.utils.crypto import get_random_string
def _put_file(self, name, content) -> str:
    # Connection must be open!
    try:
        self._mkremdirs(os.path.dirname(name))
        pwd = self._connection.pwd()
        self._connection.cwd(os.path.dirname(name))

        # Rename the new file before saving if there is already a file with an
        # identical name in the directory
        files_in_dir = self.listdir(pwd)[1]
        for file in files_in_dir:
            if file == name:
                while file == name:
                    splitted_file_str = os.path.splitext(name)
                    file_root = splitted_file_str[0]
                    file_ext = splitted_file_str[1]
                    name = "%s_%s%s" % (file_root, get_random_string(7), file_ext)**

        # Store the file
        self._connection.storbinary(
            "STOR " + os.path.basename(name),
            content.file,
            content.DEFAULT_CHUNK_SIZE,
        )
        self._connection.cwd(pwd)

        return name

....

i also changed the _save func of ftp.py to:

def _save(self, name, content):
    content.open()
    self._start_connection()
    name = self._put_file(name, content)
    content.close()
    return name

that's it. maybe this is useful for someone.

@jschneier
Copy link
Owner

Hi @HerrEich thanks for opening this. Many other backends already implement this feature as you just need to overwrite get_available_name, would you be interested in contributing it to FTP?

@HerrEich
Copy link
Author

Hi jschneider, i now know how to use github :D i am quite busy at the moment but i will probably have enough time next weekend to do it!

@HerrEich HerrEich reopened this Apr 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants