How to upload files using RPC's

Can someone guide me how to upload and handle files using frappe RPC’s and Frappe AJAX calls?

And if there is any guide how to handle files in frappe in general, I would appreciate it

Hi @mohammad-ihraiz:

Check this:
https://frappeframework.com/docs/user/en/api/rest#file-uploads

Hope this helps.

I read this, but it doesn’t apply to my situation. Let me clarify:

I’m trying to build an RPC that will be used by another application that isn’t built with Frappe—I’m just using Frappe for the backend.

If I follow the example you provided, I’d need to make two requests to the server: one to upload the file and another to call my RPC to process that file.

However, I want to achieve this in a single API call, where the file is uploaded and processed through my RPC simultaneously.

Is that possible?

Hi @mohammad-ihraiz:

Maybe I’m wrong, but I think it’s not possible without writing a custom endpoint.

Something like this:

import frappe
from frappe.utils.file_manager import save_file

@frappe.whitelist()
def upload_file():
    # Get file from request
    uploaded_file = frappe.request.files['file']
    task_subject = frappe.request.files['task_subject']
    file_name = uploaded_file.filename
    file_data = uploaded_file.read()
    
    # Create your document, here "Task"
    doc = frappe.get_doc({
        "doctype": "Task",
        "subject": "I am here, where are you?"
    })
    doc.insert()
    
    # Save the file using Frappe's file manager
    saved_file = save_file(file_name, file_data, "Task", doc.name, is_private=1)

    # Return the file URL and task name for frontend reference
    return {
        "file_url": saved_file.file_url,
        "task_name": doc.name
    }

I’ve not tested but this should work.
Again, maybe there is easier way … Many times, after struggling on something I’ve found simpler method on framework’s deep ocean :upside_down_face:

Hope this helps.

2 Likes