Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Add upload file action

mertunsall640d1a15feb9
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index f4c389dd2..d816f49fa 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -2,6 +2,7 @@ import asyncio
import enum
import json
import logging
+import os
import re
from collections.abc import Awaitable, Callable
from typing import Any, Generic, TypeVar, cast
@@ -25,6 +26,7 @@ from browser_use.controller.views import (
SendKeysAction,
StructuredOutputAction,
SwitchTabAction,
+ UploadFileAction,
)
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm.base import BaseChatModel
@@ -245,6 +247,44 @@ class Controller(Generic[Context]):
long_term_memory=f"Input '{params.text}' into element {params.index}.",
)
+ @self.registry.action('Upload file to interactive element with file path', param_model=UploadFileAction)
+ async def upload_file(params: UploadFileAction, browser_session: BrowserSession, available_file_paths: list[str]):
+ if params.path not in available_file_paths:
+ return ActionResult(error=f'File path {params.path} is not available')
+
+ if not os.path.exists(params.path):
+ return ActionResult(error=f'File {params.path} does not exist')
+
+ file_upload_dom_el = await browser_session.find_file_upload_element_by_index(
+ params.index, max_height=3, max_descendant_depth=3
+ )
+
+ if file_upload_dom_el is None:
+ msg = f'No file upload element found at index {params.index}'
+ logger.info(msg)
+ return ActionResult(error=msg)
+
+ file_upload_el = await browser_session.get_locate_element(file_upload_dom_el)
+
+ if file_upload_el is None:
+ msg = f'No file upload element found at index {params.index}'
+ logger.info(msg)
+ return ActionResult(error=msg)
+
+ try:
+ await file_upload_el.set_input_files(params.path)
+ msg = f'📁 Successfully uploaded file to index {params.index}'
+ logger.info(msg)
+ return ActionResult(
+ extracted_content=msg,
+ include_in_memory=True,
+ long_term_memory=f'Uploaded file {params.path} to element {params.index}',
+ )
+ except Exception as e:
+ msg = f'Failed to upload file to index {params.index}: {str(e)}'
+ logger.info(msg)
+ return ActionResult(error=msg)
+
# Save PDF
@self.registry.action('Save the current page as a PDF file')
async def save_pdf(page: Page):
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 73c81ca7e..5d61b92dd 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -57,6 +57,11 @@ class SendKeysAction(BaseModel):
keys: str
+class UploadFileAction(BaseModel):
+ index: int
+ path: str
+
+
class ExtractPageContentAction(BaseModel):
value: str