The uploadFile executor
Test the file upload functionality using the uploadFile executor when Send Keys does not work
The Send Keys method is commonly used in automated testing of the file upload functionality. Sometimes, the method does not work as expected with some implementations of the feature.
To handle testing in such cases, BrowserStack provides the uploadFile
JavaScript executor. You can use this executor when working with files:
Preloaded on BrowserStack remote computers
Downloaded to BrowserStack remote computers in an Automate session
Preloaded to the BrowserStack server using the Upload media file REST API
From your local computer
Presently, the uploadFile
executor works with Google Chrome (version 60 and higher) and Microsoft Edge (version 80 and higher) on Windows 10 and Windows 11 only.
The following code samples show how to use the executor:
```java
package com.browserstack;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
import java.time.Duration;
import java.util.HashMap;
public class FileUpload {
public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";
public static void main(String[] args) throws Exception {
HashMap<String, Object> bstackOptions = new HashMap<>();
ChromeOptions options = new ChromeOptions();
options.setCapability("bstack:options", bstackOptions);
bstackOptions.put("os", "Windows");
bstackOptions.put("osVersion", "10");
bstackOptions.put("projectName", "Upload Files");
bstackOptions.put("buildName", "Upload_file");
bstackOptions.put("browserName", "Chrome");
bstackOptions.put("browserVersion", "116");
WebDriver driver = new RemoteWebDriver(
new URL(URL),
options
);
driver.navigate().to("https://www.fileconvoy.com");
WebElement clickable = driver.findElement(By.id("upfile_0"));
Actions actions = new Actions(driver);
actions.moveToElement(clickable).click().perform();
((JavascriptExecutor) driver).executeScript("browserstack_executor: {" +
"\"action\": \"uploadFile\"," +
"\"arguments\": {" +
"\"fileName\":\"icon.png\"" +
"}" +
"}");
driver.findElement(By.id("readTermsOfUse")).click();
driver.findElement(By.name("upload_button")).submit();
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("TopMessage")));
if (driver.findElement(By.id("TopMessage")).getText()
.equals("Your file(s) have been successfully uploaded.")) {
((JavascriptExecutor) driver).executeScript("browserstack_executor: {" +
"\"action\": \"setSessionStatus\"," +
"\"arguments\": {" +
"\"status\": \"passed\"," +
"\"reason\": \"File uploaded!\"" +
"}" +
"}");
} else {
((JavascriptExecutor) driver).executeScript("browserstack_executor: {" +
"\"action\": \"setSessionStatus\"," +
"\"arguments\": {" +
"\"status\": \"failed\"," +
"\"reason\": \"File upload failed\"" +
"}" +
"}");
}
} catch (Exception e) {
((JavascriptExecutor) driver).executeScript("browserstack_executor: {" +
"\"action\": \"setSessionStatus\"," +
"\"arguments\": {" +
"\"status\": \"failed\"," +
"\"reason\": \"File failed to upload in 5 seconds\"" +
"}" +
"}");
}
driver.quit();
}
}
```
Copy icon
Copy
```java
const webdriver = require("selenium-webdriver");
const remote = require("selenium-webdriver/remote");
// Input capabilities
var capabilities = {
"bstack:options": {
os: "Windows",
osVersion: "10",
projectName: "Upload Files",
buildName: "Upload_file",
userName: "YOUR_USERNAME",
accessKey: "YOUR_ACCESS_KEY",
},
browserName: "Chrome",
browserVersion: "116",
};
let driver = new webdriver.Builder()
.usingServer("https://hub-cloud.browserstack.com/wd/hub")
.withCapabilities(capabilities)
.build();
//This will detect your local file
driver.setFileDetector(new remote.FileDetector());
(async () => {
await driver.get("https://www.fileconvoy.com");
const filePathElement = await driver.findElement(webdriver.By.id("upfile_0"));
const actions = driver.actions();
await actions.move({ origin: filePathElement }).press().release().perform();
await driver.executeScript(
'browserstack_executor: {"action": "uploadFile", "arguments": {"fileName":"icon.png"}}'
);
await (await driver.findElement(webdriver.By.id("readTermsOfUse"))).click();
await (await driver.findElement(webdriver.By.name("upload_button"))).click();
try {
await driver.wait(
webdriver.until.elementIsVisible(
await driver.findElement(webdriver.By.id("TopMessage"))
),
5000
);
if (
(
await driver.findElement(webdriver.By.id("TopMessage")).getText()
).includes("successfully uploaded")
) {
await driver.executeScript(
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}'
);
} else {
await driver.executeScript(
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}'
);
}
} catch (e) {
await driver.executeScript(
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File could not be uploaded in time"}}'
);
}
await driver.quit();
})();
```
Copy icon
Copy
```python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
options = Options()
desired_cap = {
"os" : "Windows",
"osVersion" : "10",
"projectName" : "Upload Files",
"buildName" : "Upload_file",
"userName": "YOUR_USERNAME",
"accessKey": "YOUR_ACCESS_KEY",
"browserName" : "Chrome",
"browserVersion" : "116",
}
options.set_capability('bstack:options', desired_cap)
driver = webdriver.Remote(
command_executor='https://hub-cloud.browserstack.com/wd/hub',
options=options)
driver.get('https://www.fileconvoy.com')
clickable = driver.find_element(By.ID, "upfile_0")
ActionChains(driver)\
.move_to_element(clickable)\
.pause(1)\
.click(clickable)\
.pause(1)\
.perform()
driver.execute_script('browserstack_executor: {"action": "uploadFile", "arguments": {"fileName":"icon.png"}}')
driver.find_element(By.ID,'readTermsOfUse').click()
driver.find_element(By.NAME,'upload_button').submit()
try:
WebDriverWait(driver, 5).until(lambda x: x.find_element(By.ID,'TopMessage'))
if(driver.find_element(By.ID, 'TopMessage').text == "Your file(s) have been successfully uploaded."):
# Setting the status of test as 'passed' or 'failed' based on the condition; if title of the web page starts with 'BrowserStack'
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "File uploaded!"}}')
else:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "File upload failed"}}')
except TimeoutException:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "File failed to upload in 5 seconds"}}')
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'selenium-webdriver'
capabilities = {
"os" => "Windows",
"osVersion" => "10",
"projectName" => "Upload Files",
"buildName" => "Upload_file",
'browserName' => 'Chrome',
'browser_version' => '116',
'userName' => 'YOUR_USERNAME',
'accessKey' => 'YOUR_ACCESS_KEY'
}
options = Selenium::WebDriver::Chrome::Options.new
options.add_option('bstack:options', capabilities)
driver = Selenium::WebDriver.for(:remote, url: 'https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub', options: options)
driver.navigate.to 'https://www.fileconvoy.com'
clickable = driver.find_element(id: 'upfile_0')
driver.action.move_to(clickable).click(clickable).perform
driver.execute_script('browserstack_executor: {"action": "uploadFile", "arguments": {"fileName":"icon.png"}}')
driver.find_element(id: 'readTermsOfUse').click
driver.find_element(name: 'upload_button').submit
begin
wait = Selenium::WebDriver::Wait.new(timeout: 5)
wait.until { driver.find_element(id: 'TopMessage') }
if driver.find_element(id: 'TopMessage').text == 'Your file(s) have been successfully uploaded.'
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status": "passed", "reason": "File uploaded!"}}')
else
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status": "failed", "reason": "File upload failed"}}')
end
rescue Selenium::WebDriver::Error::TimeOutError
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status": "failed", "reason": "File failed to upload in 5 seconds"}}')
end
driver.quit
```
Copy icon
Copy
Is this page helping you?
Thank you for your valuable feedback!