box-api

Duplicate names in Box cloud


I'm having trouble with a script for uploading files to Box Cloud. The issue is that I can't upload files with the same name, and I need to add a version number to them manually as postfix (ex. filename (1).jpeg). Right now, I'm checking all the files in my storage before uploading, find the last with uploaded name and adding a version number if needed. But this method is slow because I have to check all files every time. Especially it will become a big problem with files amount increasing. I tried searching for the files instead, but that didn't work well because new files take a while to show up in the search. Is there a better way to upload files with the same name more easily?


Solution

  • There is a preflight check in the API and the SDK's, check it out here.

    This OPTS http request will allow you to find out if the file can be accepted by the upload, you just need the filename and it's size.

    From here you can determine if you want to upload a new file or a new version.

    Box.com does have the concept of versioning, so you could avoid the file renaming entirely, depending on your use case.

    I'm not sure what you mean by script, but here is a python flavored one, using the official SDK:

    def file_upload(client: Client, file_path: str, folder: Folder) -> File:
    """upload a file to box"""
    
    file_size = os.path.getsize(file_path)
    file_name = os.path.basename(file_path)
    file = None
    try:
        folder.preflight_check(file_size, file_name)
    except BoxAPIException as err:
        if err.code == "item_name_in_use":
            file_id = err.context_info["conflicts"]["id"]
            file = client.file(file_id).get()
        else:
            raise err
    
    if file is None:
        # upload new file
        file = folder.upload(file_path, file_name)
    else:
        # upload new version
        file = file.update_contents(file_path)
    

    Let us know if this helps.