Custom File Upload to custom filePath and fileName

Hello, hope everyone is doing well.

I have been researching how to control file attachments in my custom doctype within a custom app. I would like to control the naming of the file and the folder the files end up in. I would like to use the Attach field but I don’t see any triggers that are usable in upload.js, file_manager.py, handler.py, or control.js.

I thought I would hijack the on_upload_complete from control.js. It works, I get the attachment but it is already named and stored.

Is there a way to manipulate files on the file system after they are saved?
Is there a better way to change the file name to be saved before the file is saved the first time? Using built-in functions…

I am aware I can write my own code to do all this but it would be nice if there where a before_save event triggered.

Thank you,

@NCP can you help out

I think you could create a Server Script for that. Use “File” doctype and select “After Save” as a event name.

I have the following Server Script that triggers After Insert on the File doctype

This script changes the file to public, if it was private, then renames it based on the hash.

Use it as a reference and adjust to your use case.

if doc.document_attachment:
    try:
        file_docs = frappe.get_all('File', filters={'file_url': doc.document_attachment}, fields=['name', 'is_private', 'file_url'])
        if file_docs:
            file_doc = frappe.get_doc('File', file_docs[0]['name'])
            if file_doc.is_private:
                new_file_doc = frappe.copy_doc(file_doc)
                new_file_doc.is_private = 0
                new_file_doc.file_name = f"{doc.name}_{new_file_doc.content_hash}.{new_file_doc.file_type.lower()}"
                new_file_doc.save(ignore_permissions=True)
                doc.document_attachment = new_file_doc.file_url
                doc.save(ignore_permissions=True)
                file_doc.delete(ignore_permissions=True)
        else:
            frappe.log_error("File not found.")
    except Exception as e:
        frappe.log_error(f"Error handling attachment for {doc}: {str(e)}", "Attachment Handling Exception")
1 Like

@Parth_Vashista I think it may help you.

https://github.com/kid1194/frappe-better-attach-control