Testing with preloaded files isn’t supported on Android devices.
If you are agnostic to the actual files used in the test and only care about whether the file upload works fine or not, test with files preloaded on BrowserStack remote computers. These Windows and Mac computers include the following preloaded files:
In the below remote file paths there are two \, the first \ is used as an escape character
*Video*
C:\\Users\\hello\\Documents\\video\\saper.avi
C:\\Users\\hello\\Documents\\video\\sample_mpeg4.mp4
C:\\Users\\hello\\Documents\\video\\sample_iTunes.mov
C:\\Users\\hello\\Documents\\video\\sample_mpeg2.m2v
*Images*
C:\\Users\\hello\\Documents\\images\\wallpaper1.jpg
C:\\Users\\hello\\Documents\\images\\icon.png
C:\\Users\\hello\\Documents\\images\\cartoon-animation.gif
*Documents*
C:\\Users\\hello\\Documents\\documents\\xls-sample1.xls
C:\\Users\\hello\\Documents\\documents\\text-sample1.txt
C:\\Users\\hello\\Documents\\documents\\pdf-sample1.pdf
C:\\Users\\hello\\Documents\\documents\\doc-sample1.docx
*Audio*
C:\\Users\\hello\\Documents\\audio\\first_noel.mp3
C:\\Users\\hello\\Documents\\audio\\BachCPE_SonataAmin_1.wma
C:\\Users\\hello\\Documents\\audio\\250Hz_44100Hz_16bit_05sec.wav
*Zip files*
C:\\Users\\hello\\Documents\\4KBzipFile.zip
C:\\Users\\hello\\Documents\\1MBzipFile.zip
Copy icon
Copy
*Video*
/Users/test1/Documents/video/saper.avi
/Users/test1/Documents/video/sample_mpeg4.mp4
/Users/test1/Documents/video/sample_iTunes.mov
/Users/test1/Documents/video/sample_mpeg2.m2v
*Images*
/Users/test1/Documents/images/wallpaper1.jpg
/Users/test1/Documents/images/icon.png
/Users/test1/Documents/images/cartoon-animation.gif
*Documents*
/Users/test1/Documents/documents/xls-sample1.xls
/Users/test1/Documents/documents/text-sample1.txt
/Users/test1/Documents/documents/pdf-sample1.pdf
/Users/test1/Documents/documents/doc-sample1.docx
*Audio*
/Users/test1/Documents/audio/first_noel.mp3
/Users/test1/Documents/audio/BachCPE_SonataAmin_1.wma
/Users/test1/Documents/audio/250Hz_44100Hz_16bit_05sec.wav
*Zip files*
/Users/test1/Documents/4KBzipFile.zip
/Users/test1/Documents/1MBzipFile.zip
Copy icon
Copy
To test the file upload feature, use paths to these preloaded files in your test scripts. See the following scripts for example:
Selenium 4 W3C test scripts to test on desktops
```java
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class JavaSample {
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 {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "IE");
capabilities.setCapability("browserVersion", "11.0");
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
browserstackOptions.put("os", "Windows");
browserstackOptions.put("osVersion", "10");
browserstackOptions.put("projectName", "Sample Test");
browserstackOptions.put("buildName", "Sample_test");
capabilities.setCapability("bstack:options", browserstackOptions);
RemoteWebDriver driver = new RemoteWebDriver(new URL(URL), caps);
driver.setFileDetector(new LocalFileDetector());
driver.get("https://www.fileconvoy.com/");
driver.findElement(By.id("upfile_0")).sendKeys("C:\\Users\\hello\\Documents\\audio\\first_noel.mp3"); //File path in remote machine
driver.findElement(By.id("readTermsOfUse")).click();
driver.findElement(By.name("upload_button")).submit();
JavascriptExecutor jse = (JavascriptExecutor)driver;
try {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("TopMessage")));
if(driver.findElementById("TopMessage").getText().contains("successfully uploaded")) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"File uploaded successfully\"}}");
} else {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"failed\", \"reason\": \"File upload failed\"}}");
}
}
catch(Exception e) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"failed\", \"reason\": \"File could not be uploaded in 5 seconds\"}}");
}
driver.quit();
}
}
```
Copy icon
Copy
```javascript
const webdriver = require("selenium-webdriver");
const remote = require("selenium-webdriver/remote");
// Input capabilities
var capabilities = {
'bstack:options' : {
"os" : "Windows",
"osVersion" : "10",
"projectName" : "Sample Test",
"buildName" : "Sample_test",
"userName" : "YOUR_USERNAME",
"accessKey" : "YOUR_ACCESS_KEY",
},
"browserName" : "IE",
"browserVersion" : "11.0",
}
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"));
await filePathElement.sendKeys("C:\\Users\\hello\\Documents\\audio\\first_noel.mp3");
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
```csharp
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver;
InternetExplorerOptions capabilities = new InternetExplorerOptions();
capabilities.BrowserVersion = "11.0";
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
browserstackOptions.Add("os", "Windows");
browserstackOptions.Add("osVersion", "10");
browserstackOptions.Add("projectName", "Sample Test");
browserstackOptions.Add("buildName", "Sample_test");
browserstackOptions.Add("userName", "YOUR_USERNAME");
browserstackOptions.Add("accessKey", "YOUR_ACCESS_KEY");
browserstackOptions.Add("browserName", "IE");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
driver = new RemoteWebDriver(
new Uri("https://hub.browserstack.com/wd/hub/"), capabilities
);
driver.Navigate().GoToUrl("https://www.fileconvoy.com");
IWebElement uploadFile = driver.FindElement(By.Id("upfile_0"));
Console.WriteLine(driver.Title);
String path = "C:\\Users\\hello\\Documents\\audio\\first_noel.mp3"; //File path in remote machine
LocalFileDetector detector = new LocalFileDetector();
var allowsDetection = driver as IAllowsFileDetection;
if (allowsDetection != null)
{
allowsDetection.FileDetector = new LocalFileDetector();
}
uploadFile.SendKeys(path);
driver.FindElement(By.Id("readTermsOfUse")).Click();
driver.FindElement(By.Id("upload_button")).Click();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
if (driver.FindElement(By.CssSelector("#TopMessage")).Text.Contains("successfully uploaded"))
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \"File uploaded successfully!\"}}");
}
else
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"File upload failed!\"}}");
}
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
desired_cap = {
'bstack:options' : {
"os" : "Windows",
"osVersion" : "10",
"projectName" : "Sample Test",
"buildName" : "Sample_test",
},
"browserName" : "IE",
"browserVersion" : "11.0",
}
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')
driver.find_element_by_id('upfile_0').send_keys('C:\\Users\\hello\\Documents\\audio\\first_noel.mp3') #File path in remote machine
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'
# Input capabilities
capabilities = {
'bstack:options' => {
"os" => "Windows",
"osVersion" => "10",
"projectName" => "Sample Test",
"buildName" => "Sample_test",
"javascriptEnabled" => "true"
},
"browserName" => "IE",
"browserVersion" => "11.0",
}
driver = Selenium::WebDriver.for(
:remote,
:url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
:capabilities => capabilities
)
driver.file_detector = lambda do |args|
str = args.first.to_s
str if File.exist?(str)
end
driver.navigate.to "https://www.fileconvoy.com"
driver.find_element(:id, "upfile_0").send_keys("C:\\Users\\hello\\Documents\\audio\\first_noel.mp3") #File path in remote machine
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element(:name, "upload_button").submit
sleep(5)
driver.quit
```
Copy icon
Copy
Selenium 4 W3C test scripts to test on iOS devices
```java
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.net.MalformedURLException;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import io.appium.java_client.MobileBy;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import org.apache.commons.lang3.*;
public class Upload extends Thread{
public static String userName = "YOUR_USERNAME";
public static String accessKey = "YOUR_ACCESS_KEY";
public static void main(String args[]) throws MalformedURLException, InterruptedException {
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
browserstackOptions.put("osVersion", "14");
browserstackOptions.put("deviceName", "iPhone 12");
browserstackOptions.put("realMobile", "true");
browserstackOptions.put("projectName", "Sample Test");
browserstackOptions.put("buildName", "Sample_test");
browserstackOptions.put("debug", "true");
capabilities.setCapability("bstack:options", browserstackOptions);
IOSDriver<IOSElement> driver = new IOSDriver<IOSElement>(new URL("https://"+userName+":"+accessKey+"@hub-cloud.browserstack.com/wd/hub"), caps);
driver.get("https://the-internet.herokuapp.com/upload");
Thread.sleep(5000);
driver.findElement(By.id("file-upload")).click();
driver.context("NATIVE_APP");
driver.findElement(By.name("Photo Library")).click();
Thread.sleep(5000);
List list = driver.findElements(By.className("XCUIElementTypeImage"));
((IOSElement) list.get(0)).click();
Thread.sleep(5000);
driver.findElement(By.name("Choose")).click();
Set<String> contextName = driver.getContextHandles();
driver.context(contextName.toArray()[1].toString());
driver.findElement(By.id("file-submit")).click();
driver.quit();
}
}
```
Copy icon
Copy
```javascript
var wd = require('wd');
// Input capabilities
var capabilities = {
'bstack:options' : {
"osVersion" : "14",
"deviceName" : "iPhone 12",
"realMobile" : "true",
"projectName" : "Sample Test",
"buildName" : "Sample_test",
"debug" : "true",
},
"browserName" : "safari",
}
async function runTestWithCaps () {
let driver = new webdriver.Builder()
.usingServer('https://hub-cloud.browserstack.com/wd/hub')
.withCapabilities(capabilities)
.build();
await driver.get("https://the-internet.herokuapp.com/upload")
await new Promise(r => setTimeout(r, 2000));
element = await driver.waitForElementById('file-upload')
await element.click()
await driver.context('NATIVE_APP')
element = await driver.waitForElementByName('Photo Library')
await element.click()
await new Promise(r => setTimeout(r, 2000));
element = await driver.elementsByClassName('XCUIElementTypeImage')
await element[0].click()
await new Promise(r => setTimeout(r, 5000));
element = await driver.waitForElementByName('Choose')
await element.click()
await new Promise(r => setTimeout(r, 10000));
contexts = await driver.contexts();
await driver.context(contexts[1])
element = await driver.waitForElementById("file-submit")
await element.click()
await driver.quit();
}
runTestWithCaps();
```
Copy icon
Copy
```csharp
using System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.iOS;
namespace SampleTests
{
class UploadFile
{
static void Main(string[] args)
{
AppiumDriver<IWebElement> driver;
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
browserstackOptions.Add("osVersion", "14");
browserstackOptions.Add("deviceName", "iPhone 12");
browserstackOptions.Add("realMobile", "true");
browserstackOptions.Add("projectName", "Sample Test");
browserstackOptions.Add("buildName", "Sample_test");
browserstackOptions.Add("debug", "true");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
driver = new IOSDriver<IWebElement>(
new Uri("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub/"), capability
);
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
Thread.Sleep(10000);
driver.FindElementById("file-upload").Click();
driver.Context = "NATIVE_APP";
driver.FindElement(By.Name("Photo Library")).Click();
Thread.Sleep(5000);
IWebElement element = driver.FindElementsByClassName("XCUIElementTypeImage")[0];
element.Click();
driver.FindElementByName("Choose").Click();
driver.Context = driver.Contexts[1];
Console.WriteLine(driver.Title);
driver.FindElementById("file-submit").Click();
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common import action_chains, keys
from time import sleep
from selenium.webdriver.common.by import By
desired_cap = {
'bstack:options' : {
"osVersion" : "14",
"deviceName" : "iPhone 12",
"realMobile" : "true",
"projectName" : "Sample Test",
"buildName" : "Sample_test",
"debug" : "true",
},
}
options.set_capability('bstack:options', desired_cap)
driver = webdriver.Remote(
command_executor='https://hub-cloud.browserstack.com/wd/hub',
options=options)
driver.get("https://the-internet.herokuapp.com/upload")
sleep(10)
driver.find_element_by_id('file-upload').click()
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name('Photo Library').click()
sleep(5)
elements = driver.find_elements_by_class_name("XCUIElementTypeImage")
elements[0].click() # 1 represents second element from the list of 9 preloaded images and videos
sleep(5)
driver.find_element_by_name("Choose").click()
sleep(10)
driver.switch_to.context(driver.contexts[1])
driver.find_element_by_id("file-submit").click()
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'appium_lib'
# Input capabilities
capabilities = {
'bstack:options' => {
"osVersion" => "14",
"deviceName" => "iPhone 12",
"realMobile" => "true",
"projectName" => "Sample Test",
"buildName" => "Sample_test",
"debug" => "true",
},
}
appium_driver = Appium::Driver.new({'caps' => capabilities,'appium_lib' => {:server_url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"}}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://the-internet.herokuapp.com/upload"
sleep(5)
driver.find_element(xpath: "//*[@id='file-upload']").click
driver.set_context('NATIVE_APP')
sleep(10)
driver.find_element(name: "Photo Library").click
sleep(5)
elements=driver.find_elements(:class_name,"XCUIElementTypeImage")
elements[0].click
driver.find_element(name: "Choose").click
contexts = driver.available_contexts
driver.set_context contexts[1]
driver.find_element(:id,"file-submit").click()
driver.quit()
```
Copy icon
Copy
Selenium Legacy JSON test scripts to test on desktops
```java
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class JavaSample {
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 {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browser", "internet explorer");
caps.setCapability("os", "windows");
caps.setCapability("browser_version", "11.0");
caps.setCapability("os_version", "10");
caps.setCapability("browserstack.sendKeys", "true");
caps.setCapability("browserstack.debug", "true");
caps.setCapability("name", "Bstack-[Java] Sample Test");
RemoteWebDriver driver = new RemoteWebDriver(new URL(URL), caps);
driver.setFileDetector(new LocalFileDetector());
driver.get("https://www.fileconvoy.com/");
driver.findElement(By.id("upfile_0")).sendKeys("C:\\Users\\hello\\Documents\\audio\\first_noel.mp3"); //File path in remote machine
driver.findElement(By.id("readTermsOfUse")).click();
driver.findElement(By.name("upload_button")).submit();
JavascriptExecutor jse = (JavascriptExecutor)driver;
try {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("TopMessage")));
if(driver.findElementById("TopMessage").getText().contains("successfully uploaded")) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"File uploaded successfully\"}}");
} else {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"failed\", \"reason\": \"File upload failed\"}}");
}
}
catch(Exception e) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"failed\", \"reason\": \"File could not be uploaded in 5 seconds\"}}");
}
driver.quit();
}
}
```
Copy icon
Copy
```javascript
const webdriver = require("selenium-webdriver");
const remote = require("selenium-webdriver/remote");
// Input capabilities
const capabilities = {
"browserName": "Internet Explorer",
"browser_version": "11.0",
"os": "Windows",
"os_version": "10",
"name": "Bstack-[NodeJS] Upload Test",
"browserstack.sendKeys": "true",
"browserstack.debug": "true",
"browserstack.user": "YOUR_USERNAME",
"browserstack.key": "YOUR_ACCESS_KEY"
};
const 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"));
await filePathElement.sendKeys("C:\\Users\\hello\\Documents\\audio\\first_noel.mp3");
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
```csharp
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver;
OpenQA.Selenium.IE.InternetExplorerOptions capability = new OpenQA.Selenium.IE.InternetExplorerOptions();
capability.AddAdditionalCapability("browser", "IE", true);
capability.AddAdditionalCapability("browser_version", "11", true);
capability.AddAdditionalCapability("os", "Windows", true);
capability.AddAdditionalCapability("os_version", "10", true);
capability.AddAdditionalCapability("browserstack.sendKeys", "true", true);
capability.AddAdditionalCapability("browserstack.debug", "true", true);
capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME", true);
capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY", true);
capability.AddAdditionalCapability("name", "Bstack-[C_sharp] Sample Test", true);
driver = new RemoteWebDriver(
new Uri("https://hub-cloud.browserstack.com/wd/hub/"), capability
);
driver.Navigate().GoToUrl("https://www.fileconvoy.com");
IWebElement uploadFile = driver.FindElement(By.Id("upfile_0"));
Console.WriteLine(driver.Title);
String path = "C:\\Users\\hello\\Documents\\audio\\first_noel.mp3"; //File path in remote machine
LocalFileDetector detector = new LocalFileDetector();
var allowsDetection = driver as IAllowsFileDetection;
if (allowsDetection != null)
{
allowsDetection.FileDetector = new LocalFileDetector();
}
uploadFile.SendKeys(path);
driver.FindElement(By.Id("readTermsOfUse")).Click();
driver.FindElement(By.Id("upload_button")).Click();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
if (driver.FindElement(By.CssSelector("#TopMessage")).Text.Contains("successfully uploaded"))
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \"File uploaded successfully!\"}}");
}
else
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"File upload failed!\"}}");
}
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
desired_cap = {
'browser': 'Internet Explorer',
'browser_version': '11.0',
'os': 'Windows',
'os_version': '10',
'browserstack.sendKeys': 'true',
'browserstack.debug': 'true',
'name': 'Bstack-[Python] Sample Test'
}
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub',
desired_capabilities=desired_cap)
driver.get('https://www.fileconvoy.com')
driver.find_element_by_id('upfile_0').send_keys('C:\\Users\\hello\\Documents\\audio\\first_noel.mp3') #File path in remote machine
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'
# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['browser'] = 'Internet Explorer'
caps['browser_version'] = '11.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['name'] = 'Bstack-[Ruby] Sample Test'
caps['browserstack.sendKeys'] = 'true'
caps['browserstack.debug'] = 'true'
caps["javascriptEnabled"]='true' #Enabling the javascriptEnabled capability to execute javascript in the test script
driver = Selenium::WebDriver.for(:remote,
:url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
:desired_capabilities => caps)
driver.file_detector = lambda do |args|
str = args.first.to_s
str if File.exist?(str)
end
driver.navigate.to "https://www.fileconvoy.com"
driver.find_element(:id, "upfile_0").send_keys("C:\\Users\\hello\\Documents\\audio\\first_noel.mp3") #File path in remote machine
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element(:name, "upload_button").submit
sleep(5)
driver.quit
```
Copy icon
Copy
Selenium Legacy JSON test scripts to test on iOS devices
```java
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.net.MalformedURLException;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import io.appium.java_client.MobileBy;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import org.apache.commons.lang3.*;
public class Upload extends Thread{
public static String userName = "YOUR_USERNAME";
public static String accessKey = "YOUR_ACCESS_KEY";
public static void main(String args[]) throws MalformedURLException, InterruptedException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("device", "iPhone 12 Pro Max");
caps.setCapability("os_version", "14");
caps.setCapability("real_mobile", "true");
caps.setCapability("project", "My First Project");
caps.setCapability("build", "My First Build");
caps.setCapability("name", "Bstack-[Java] Sample Test");
caps.setCapability("nativeWebTap", "true");
IOSDriver<IOSElement> driver = new IOSDriver<IOSElement>(new URL("https://"+userName+":"+accessKey+"@hub-cloud.browserstack.com/wd/hub"), caps);
driver.get("https://the-internet.herokuapp.com/upload");
Thread.sleep(5000);
driver.findElement(By.id("file-upload")).click();
driver.context("NATIVE_APP");
driver.findElement(By.name("Photo Library")).click();
Thread.sleep(5000);
List list = driver.findElements(By.className("XCUIElementTypeImage"));
((IOSElement) list.get(0)).click();
Thread.sleep(5000);
driver.findElement(By.name("Choose")).click();
Set<String> contextName = driver.getContextHandles();
driver.context(contextName.toArray()[1].toString());
driver.findElement(By.id("file-submit")).click();
driver.quit();
}
}
```
Copy icon
Copy
```javascript
var wd = require('wd');
// Input capabilities
const capabilities = {
'device' : 'iPhone 12',
'realMobile' : 'true',
'os_version' : '14.0',
'browserName' : 'iPhone',
'name': 'BStack-[NodeJS] Sample Test',
'build': 'BStack Build Number 1',
"nativeWebTap":true
}
async function runTestWithCaps () {
let driver = wd.promiseRemote("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub");
await driver.init(capabilities);
await driver.get("https://the-internet.herokuapp.com/upload")
await new Promise(r => setTimeout(r, 2000));
element = await driver.waitForElementById('file-upload')
await element.click()
await driver.context('NATIVE_APP')
element = await driver.waitForElementByName('Photo Library')
await element.click()
await new Promise(r => setTimeout(r, 2000));
element = await driver.elementsByClassName('XCUIElementTypeImage')
await element[0].click()
await new Promise(r => setTimeout(r, 5000));
element = await driver.waitForElementByName('Choose')
await element.click()
await new Promise(r => setTimeout(r, 10000));
contexts = await driver.contexts();
await driver.context(contexts[1])
element = await driver.waitForElementById("file-submit")
await element.click()
await driver.quit();
}
runTestWithCaps();
```
Copy icon
Copy
```csharp
using System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.iOS;
namespace SampleTests
{
class UploadFile
{
static void Main(string[] args)
{
AppiumDriver<IWebElement> driver;
AppiumOptions capability = new AppiumOptions();
capability.AddAdditionalCapability("browserName", "iPhone");
capability.AddAdditionalCapability("device", "iPhone 12");
capability.AddAdditionalCapability("realMobile", "true");
capability.AddAdditionalCapability("os_version", "14");
capability.AddAdditionalCapability("browserstack.debug", "true");
capability.AddAdditionalCapability("nativeWebTap", "true");
driver = new IOSDriver<IWebElement>(
new Uri("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub/"), capability
);
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
Thread.Sleep(10000);
driver.FindElementById("file-upload").Click();
driver.Context = "NATIVE_APP";
driver.FindElement(By.Name("Photo Library")).Click();
Thread.Sleep(5000);
IWebElement element = driver.FindElementsByClassName("XCUIElementTypeImage")[0];
element.Click();
driver.FindElementByName("Choose").Click();
driver.Context = driver.Contexts[1];
Console.WriteLine(driver.Title);
driver.FindElementById("file-submit").Click();
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common import action_chains, keys
from time import sleep
from selenium.webdriver.common.by import By
desired_cap = {
"device": "iPhone 12 Pro max",
"os_version": "14",
"real_mobile": "true",
"browserstack.debug": "true",
"nativeWebTap":"true"
}
driver = webdriver.Remote(command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub', desired_capabilities=desired_cap)
driver.get("https://the-internet.herokuapp.com/upload")
sleep(10)
driver.find_element_by_id('file-upload').click()
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name('Photo Library').click()
sleep(5)
elements = driver.find_elements_by_class_name("XCUIElementTypeImage")
elements[0].click() # 1 represents second element from the list of 9 preloaded images and videos
sleep(5)
driver.find_element_by_name("Choose").click()
sleep(10)
driver.switch_to.context(driver.contexts[1])
driver.find_element_by_id("file-submit").click()
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'appium_lib'
# Input capabilities
caps = {}
caps['device'] = 'iPhone 12'
caps['os_version'] = '14'
caps['platformName'] = 'iOS'
caps['realMobile'] = 'true'
caps['name'] = 'BStack-[Ruby] Sample Test' # test name
caps['build'] = 'BStack Build Number 1' # CI/CD job or build name
caps['nativeWebTap'] = 'true'
appium_driver = Appium::Driver.new({'caps' => caps,'appium_lib' => {:server_url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"}}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://the-internet.herokuapp.com/upload"
sleep(5)
driver.find_element(xpath: "//*[@id='file-upload']").click
driver.set_context('NATIVE_APP')
sleep(10)
driver.find_element(name: "Photo Library").click
sleep(5)
elements=driver.find_elements(:class_name,"XCUIElementTypeImage")
elements[0].click
driver.find_element(name: "Choose").click
contexts = driver.available_contexts
driver.set_context contexts[1]
driver.find_element(:id,"file-submit").click()
driver.quit()
```
Copy icon
Copy
Testing with files downloaded in the same Automate session isn’t supported on Android devices.
Suppose your test includes downloading a file from the web. The file is downloaded to the following location on the BrowserStack remote computer:
Downloading a file from the web slows down the execution of your tests considerably.
Within the same Automate session, the file is available in later test steps. So, you can use the downloaded file to test your file upload feature.
See the sample scripts provided for desktop testing with preloaded files, for example. Instead of the path to the preloaded file, you have to use the path to the downloaded file.
When testing on an iOS device, you have to similarly modify your script to access the recently downloaded file and upload it to the web app you want to test. See the following sample scripts:
If you are using iOS 15, add the NATIVE_APP
context after initiating the web app, and replace the ElementID file-upload
with Choose file
in the sample script.
Selenium 4 W3C test scripts to test on iOS devices
```java
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.net.MalformedURLException;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import io.appium.java_client.MobileBy;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import org.apache.commons.lang3.*;
public class Upload extends Thread{
public static String userName = "YOUR_USERNAME";
public static String accessKey = "YOUR_ACCESS_KEY";
public static void main(String args[]) throws MalformedURLException, InterruptedException {
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
browserstackOptions.put("osVersion", "14");
browserstackOptions.put("deviceName", "iPhone 12");
browserstackOptions.put("realMobile", "true");
browserstackOptions.put("projectName", "Upload Files");
browserstackOptions.put("buildName", "Upload_file");
browserstackOptions.put("debug", "true");
capabilities.setCapability("bstack:options", browserstackOptions);
IOSDriver<IOSElement> driver = new IOSDriver<IOSElement>(new URL("https://"+userName+":"+accessKey+"@hub-cloud.browserstack.com/wd/hub"), caps);
driver.get("https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv");
driver.context("NATIVE_APP");
IOSElement download = (IOSElement) new WebDriverWait(driver, 30).until(
ExpectedConditions.elementToBeClickable(MobileBy.name("Download")));
driver.findElementByName("Download").click();
Set<String> contextNames = driver.getContextHandles();
driver.context(contextNames.toArray()[1].toString());
driver.get("https://the-internet.herokuapp.com/upload");
Thread.sleep(5000);
driver.findElement(By.id("file-upload")).click();
driver.context("NATIVE_APP");
driver.findElement(By.name("Browse")).click();
Thread.sleep(5000);
driver.findElement(By.name("Recents")).click();
Thread.sleep(5000);
IOSElement elem=driver.findElement(By.xpath("//XCUIElementTypeCollectionView"));
List list=elem.findElements(By.xpath("//XCUIElementTypeCell"));
((WebElement) list.get(0)).click();
Thread.sleep(5000);
Set<String> contextName = driver.getContextHandles();
driver.context(contextName.toArray()[1].toString());
driver.findElement(By.id("file-submit")).click();
driver.quit();
}
}
```
Copy icon
Copy
```javascript
var wd = require('wd');
// Input capabilities
var capabilities = {
'bstack:options' : {
"osVersion" : "14",
"deviceName" : "iPhone 12",
"realMobile" : "true",
"projectName" : "Upload Files",
"buildName" : "Upload_file",
"debug" : "true",
},
"browserName" : "safari",
}
async function runTestWithCaps () {
let driver = new webdriver.Builder()
.usingServer('https://hub-cloud.browserstack.com/wd/hub')
.withCapabilities(capabilities)
.build();
await driver.get("https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv");
await new Promise(r => setTimeout(r, 2000));
await driver.context('NATIVE_APP');
let element = await driver.waitForElementByName('Download');
await element.click()
let contexts = await driver.contexts();
await driver.context(contexts[1]);
await new Promise(r => setTimeout(r, 2000));
await driver.get("https://the-internet.herokuapp.com/upload")
await new Promise(r => setTimeout(r, 2000));
element = await driver.waitForElementById('file-upload')
await element.click()
await driver.context('NATIVE_APP')
element = await driver.waitForElementByName('Browse')
await element.click()
await new Promise(r => setTimeout(r, 2000));
element = await driver.waitForElementByName('Recents')
await element.click()
element = await driver.waitForElementByXPath('//XCUIElementTypeCollectionView')
await new Promise(r => setTimeout(r, 2000));
let elements = await element.elementsByXPath("//XCUIElementTypeCell")
await elements[0].click()
contexts = await driver.contexts();
await driver.context(contexts[1])
element = await driver.waitForElementById("file-submit")
await element.click()
await driver.quit();
}
runTestWithCaps();
```
Copy icon
Copy
```csharp
using System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.iOS;
namespace SampleTests
{
class UploadFile
{
static void Main(string[] args)
{
AppiumDriver<IWebElement> driver;
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
browserstackOptions.Add("osVersion", "14");
browserstackOptions.Add("deviceName", "iPhone 12");
browserstackOptions.Add("realMobile", "true");
browserstackOptions.Add("projectName", "Upload Files");
browserstackOptions.Add("buildName", "Upload_file");
browserstackOptions.Add("debug", "true");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
driver = new IOSDriver<IWebElement>(
new Uri("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub/"), capability
);
driver.Navigate().GoToUrl("https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv");
driver.Context = "NATIVE_APP";
driver.FindElement(By.Name("Download")).Click();
driver.Context = driver.Contexts[1];
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
Thread.Sleep(10000);
driver.FindElementById("file-upload").Click();
driver.Context = "NATIVE_APP";
driver.FindElement(By.Name("Browse")).Click();
driver.FindElement(By.Name("Recents")).Click();
IWebElement element = driver.FindElementByXPath("//XCUIElementTypeCollectionView");
element.FindElements(By.XPath("//XCUIElementTypeCell"))[0].Click();
driver.Context = driver.Contexts[1];
Console.WriteLine(driver.Title);
driver.FindElementById("file-submit").Click();
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common import action_chains, keys
from time import sleep
from selenium.webdriver.common.by import By
desired_cap = {
'bstack:options' : {
"osVersion" : "14",
"deviceName" : "iPhone 12",
"realMobile" : "true",
"projectName" : "Upload Files",
"buildName" : "Upload_file",
"debug" : "true",
},
}
options.set_capability('bstack:options', desired_cap)
driver = webdriver.Remote(
command_executor='https://hub-cloud.browserstack.com/wd/hub',
options=options)
# download file
driver.get("https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv")
# accept download
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name('Download').click()
driver.switch_to.context(driver.contexts[1])
# go to upload url
driver.get("https://the-internet.herokuapp.com/upload")
sleep(10)
driver.find_element_by_id('file-upload').click()
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name('Browse').click()
driver.find_element_by_name('Recents').click()
element = driver.find_element_by_xpath("//XCUIElementTypeCollectionView")
print(type(element))
element.find_elements_by_xpath("//XCUIElementTypeCell")[0].click()
driver.switch_to.context(driver.contexts[1])
driver.find_element_by_id("file-submit").click()
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'appium_lib'
# Input capabilities
capabilities = {
'bstack:options' => {
"osVersion" => "14",
"deviceName" => "iPhone 12",
"realMobile" => "true",
"projectName" => "Upload Files",
"buildName" => "Upload_file",
"debug" => "true",
},
}
appium_driver = Appium::Driver.new({'caps' => capabilities,'appium_lib' => {:server_url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"}}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv"
driver.set_context('NATIVE_APP')
driver.find_element(xpath: "//*[@name='Download']").click
contexts = driver.available_contexts
driver.set_context contexts[1]
driver.navigate.to "https://the-internet.herokuapp.com/upload"
sleep(5)
driver.find_element(xpath: "//*[@id='file-upload']").click
driver.set_context('NATIVE_APP')
sleep(10)
driver.find_element(xpath: "//*[@name='Browse']").click
sleep(5)
driver.find_element(xpath: "//*[@name='Recents']").click
element=driver.find_element(:xpath,"//XCUIElementTypeCollectionView")
element.find_elements(xpath: "//XCUIElementTypeCell")[0].click
contexts = driver.available_contexts
driver.set_context contexts[1]
driver.find_element(:id,"file-submit").click()
driver.quit()
```
Copy icon
Copy
Selenium Legacy JSON test scripts to test on iOS devices
```java
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.net.MalformedURLException;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import io.appium.java_client.MobileBy;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import org.apache.commons.lang3.*;
public class Upload extends Thread{
public static String userName = "YOUR_USERNAME";
public static String accessKey = "YOUR_ACCESS_KEY";
public static void main(String args[]) throws MalformedURLException, InterruptedException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("device", "iPhone 12");
caps.setCapability("os_version", "14");
caps.setCapability("real_mobile", "true");
caps.setCapability("project", "My First Project");
caps.setCapability("build", "My First Build");
caps.setCapability("name", "Bstack-[Java] Sample Test");
caps.setCapability("nativeWebTap", "true");
IOSDriver<IOSElement> driver = new IOSDriver<IOSElement>(new URL("https://"+userName+":"+accessKey+"@hub-cloud.browserstack.com/wd/hub"), caps);
driver.get("https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv");
driver.context("NATIVE_APP");
IOSElement download = (IOSElement) new WebDriverWait(driver, 30).until(
ExpectedConditions.elementToBeClickable(MobileBy.name("Download")));
driver.findElementByName("Download").click();
Set<String> contextNames = driver.getContextHandles();
driver.context(contextNames.toArray()[1].toString());
driver.get("https://the-internet.herokuapp.com/upload");
Thread.sleep(5000);
driver.findElement(By.id("file-upload")).click();
driver.context("NATIVE_APP");
driver.findElement(By.name("Browse")).click();
Thread.sleep(5000);
driver.findElement(By.name("Recents")).click();
Thread.sleep(5000);
IOSElement elem=driver.findElement(By.xpath("//XCUIElementTypeCollectionView"));
List list=elem.findElements(By.xpath("//XCUIElementTypeCell"));
((WebElement) list.get(0)).click();
Thread.sleep(5000);
Set<String> contextName = driver.getContextHandles();
driver.context(contextName.toArray()[1].toString());
driver.findElement(By.id("file-submit")).click();
driver.quit();
}
}
```
Copy icon
Copy
```javascript
var wd = require('wd');
// Input capabilities
const capabilities = {
'device' : 'iPhone 12',
'realMobile' : 'true',
'os_version' : '14.0',
'browserName' : 'iPhone',
'name': 'BStack-[NodeJS] Sample Test',
'build': 'BStack Build Number 1',
"nativeWebTap":true
}
async function runTestWithCaps () {
let driver = wd.promiseRemote("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub");
await driver.init(capabilities);
await driver.get("https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv");
await new Promise(r => setTimeout(r, 2000));
await driver.context('NATIVE_APP');
let element = await driver.waitForElementByName('Download');
await element.click()
let contexts = await driver.contexts();
await driver.context(contexts[1]);
await new Promise(r => setTimeout(r, 2000));
await driver.get("https://the-internet.herokuapp.com/upload")
await new Promise(r => setTimeout(r, 2000));
element = await driver.waitForElementById('file-upload')
await element.click()
await driver.context('NATIVE_APP')
element = await driver.waitForElementByName('Browse')
await element.click()
await new Promise(r => setTimeout(r, 2000));
element = await driver.waitForElementByName('Recents')
await element.click()
element = await driver.waitForElementByXPath('//XCUIElementTypeCollectionView')
await new Promise(r => setTimeout(r, 2000));
let elements = await element.elementsByXPath("//XCUIElementTypeCell")
await elements[0].click()
contexts = await driver.contexts();
await driver.context(contexts[1])
element = await driver.waitForElementById("file-submit")
await element.click()
await driver.quit();
}
runTestWithCaps();
```
Copy icon
Copy
```csharp
using System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.iOS;
namespace SampleTests
{
class UploadFile
{
static void Main(string[] args)
{
AppiumDriver<IWebElement> driver;
AppiumOptions capability = new AppiumOptions();
capability.AddAdditionalCapability("browserName", "iPhone");
capability.AddAdditionalCapability("device", "iPhone 12");
capability.AddAdditionalCapability("realMobile", "true");
capability.AddAdditionalCapability("os_version", "14");
capability.AddAdditionalCapability("browserstack.debug", "true");
capability.AddAdditionalCapability("nativeWebTap", "true");
driver = new IOSDriver<IWebElement>(
new Uri("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub/"), capability
);
driver.Navigate().GoToUrl("https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv");
driver.Context = "NATIVE_APP";
driver.FindElement(By.Name("Download")).Click();
driver.Context = driver.Contexts[1];
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
Thread.Sleep(10000);
driver.FindElementById("file-upload").Click();
driver.Context = "NATIVE_APP";
driver.FindElement(By.Name("Browse")).Click();
driver.FindElement(By.Name("Recents")).Click();
IWebElement element = driver.FindElementByXPath("//XCUIElementTypeCollectionView");
element.FindElements(By.XPath("//XCUIElementTypeCell"))[0].Click();
driver.Context = driver.Contexts[1];
Console.WriteLine(driver.Title);
driver.FindElementById("file-submit").Click();
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from appium import webdriver
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common import action_chains, keys
from time import sleep
from selenium.webdriver.common.by import By
desired_cap = {
"device": "iPhone 12",
"os_version": "14",
"real_mobile": "true",
"browserstack.debug": "true",
"nativeWebTap":"true"
}
driver = webdriver.Remote(command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub', desired_capabilities=desired_cap)
# download file
driver.get("https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv")
# accept download
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name('Download').click()
driver.switch_to.context(driver.contexts[1])
# go to upload url
driver.get("https://the-internet.herokuapp.com/upload")
sleep(10)
driver.find_element_by_id('file-upload').click()
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name('Browse').click()
driver.find_element_by_name('Recents').click()
element = driver.find_element_by_xpath("//XCUIElementTypeCollectionView")
print(type(element))
element.find_elements_by_xpath("//XCUIElementTypeCell")[0].click()
driver.switch_to.context(driver.contexts[1])
driver.find_element_by_id("file-submit").click()
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'appium_lib'
# Input capabilities
caps = {}
caps['device'] = 'iPhone 12'
caps['os_version'] = '14'
caps['platformName'] = 'iOS'
caps['realMobile'] = 'true'
caps['name'] = 'BStack-[Ruby] Sample Test' # test name
caps['build'] = 'BStack Build Number 1' # CI/CD job or build name
caps['nativeWebTap'] = 'true'
appium_driver = Appium::Driver.new({'caps' => caps,'appium_lib' => {:server_url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"}}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://support.staffbase.com/hc/en-us/article_attachments/360009197031/username.csv"
driver.set_context('NATIVE_APP')
driver.find_element(xpath: "//*[@name='Download']").click
contexts = driver.available_contexts
driver.set_context contexts[1]
driver.navigate.to "https://the-internet.herokuapp.com/upload"
sleep(5)
driver.find_element(xpath: "//*[@id='file-upload']").click
driver.set_context('NATIVE_APP')
sleep(10)
driver.find_element(xpath: "//*[@name='Browse']").click
sleep(5)
driver.find_element(xpath: "//*[@name='Recents']").click
element=driver.find_element(:xpath,"//XCUIElementTypeCollectionView")
element.find_elements(xpath: "//XCUIElementTypeCell")[0].click
contexts = driver.available_contexts
driver.set_context contexts[1]
driver.find_element(:id,"file-submit").click()
driver.quit()
```
Copy icon
Copy
If you want to use your own files for a test, there are two ways to do it:
Upload files from your computer to the remote BrowserStack computer during the test.
Preload files from your computer to the BrowserStack server, and then access the files during the test.
You can upload up to 10 media files to the BrowserStack server. By default, files are deleted from the server after 30 days from the date of upload.
Upload files to the remote computer
For this, you have to use these two methods in your test script:
Local File Detector , to detect files on a local computer
Send Keys , to specify the location of the files
The Local File Detector method works for testing on Windows and Mac computers. It doesn’t work with mobile (both Android and iOS) browsers.
See the following sample scripts for reference:
Selenium 4 W3C test scripts to test on desktops
```java
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class JavaSample {
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 {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "IE");
capabilities.setCapability("browserVersion", "11.0");
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
browserstackOptions.put("os", "Windows");
browserstackOptions.put("osVersion", "10");
browserstackOptions.put("projectName", "Upload Files");
browserstackOptions.put("buildName", "Upload_file");
capabilities.setCapability("bstack:options", browserstackOptions);
RemoteWebDriver driver = new RemoteWebDriver(new URL(URL), capabilities);
driver.setFileDetector(new LocalFileDetector());
driver.get("https://www.fileconvoy.com/");
driver.findElement(By.id("upfile_0")).sendKeys("//local//file//path");
driver.findElement(By.id("readTermsOfUse")).click();
driver.findElement(By.name("upload_button")).submit();
JavascriptExecutor jse = (JavascriptExecutor)driver;
try {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("TopMessage")));
if(driver.findElementById("TopMessage").getText().contains("successfully uploaded")) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"File uploaded successfully\"}}");
} else {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"failed\", \"reason\": \"File upload failed\"}}");
}
}
catch(Exception e) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"failed\", \"reason\": \"File could not be uploaded in 5 seconds\"}}");
}
driver.quit();
}
}
```
Copy icon
Copy
```javascript
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" : "IE",
"browserVersion" : "11.0",
}
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"));
await filePathElement.sendKeys("//local//file//path");
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
```csharp
using System;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
IWebDriver driver;
InternetExplorerOptions capabilities = new InternetExplorerOptions();
capabilities.BrowserVersion = "11.0";
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
browserstackOptions.Add("os", "Windows");
browserstackOptions.Add("osVersion", "10");
browserstackOptions.Add("projectName", "Upload Files");
browserstackOptions.Add("buildName", "Upload_file");
browserstackOptions.Add("userName", "YOUR_USERNAME");
browserstackOptions.Add("accessKey", "YOUR_ACCESS_KEY");
browserstackOptions.Add("browserName", "IE");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
driver = new RemoteWebDriver(
new Uri("https://hub.browserstack.com/wd/hub/"), capabilities
);
driver.Navigate().GoToUrl("https://www.fileconvoy.com");
IWebElement uploadFile = driver.FindElement(By.Id("upfile_0"));
Console.WriteLine(driver.Title);
String path = "//path//to//your//local//file"; //File path in your local machine
LocalFileDetector detector = new LocalFileDetector();
var allowsDetection = driver as IAllowsFileDetection;
if (allowsDetection != null)
{
allowsDetection.FileDetector = detector;
}
uploadFile.SendKeys(path);
driver.FindElement(By.Id("readTermsOfUse")).Click();
driver.FindElement(By.Id("upload_button")).Click();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
if (driver.FindElement(By.CssSelector("#TopMessage")).Text.Contains("successfully uploaded"))
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \"File uploaded successfully!\"}}");
}
else
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"File upload failed!\"}}");
}
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
desired_cap = {
'bstack:options' : {
"os" : "Windows",
"osVersion" : "10",
"projectName" : "Upload Files",
"buildName" : "Upload_file",
},
"browserName" : "IE",
"browserVersion" : "11.0",
}
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')
driver.find_element_by_id('upfile_0').send_keys('//local//file//path')
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'
# Input capabilities
capabilities = {
'bstack:options' => {
"os" => "Windows",
"osVersion" => "10",
"projectName" => "Upload Files",
"buildName" => "Upload_file",
"javascriptEnabled" => "true"
},
"browserName" => "IE",
"browserVersion" => "11.0",
}
driver = Selenium::WebDriver.for(
:remote,
:url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
:capabilities => capabilities
)
driver.file_detector = lambda do |args|
str = args.first.to_s
str if File.exist?(str)
end
driver.navigate.to "https://www.fileconvoy.com"
driver.find_element(:id, "upfile_0").send_keys("//local//file//path")
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element(:name, "upload_button").submit
sleep(5)
driver.quit
```
Copy icon
Copy
Selenium Legacy JSON test scripts to test on desktops
```java
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class JavaSample {
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 {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browser", "internet explorer");
caps.setCapability("os", "windows");
caps.setCapability("browser_version", "11.0");
caps.setCapability("os_version", "10");
caps.setCapability("browserstack.sendKeys", "true");
caps.setCapability("browserstack.debug", "true");
caps.setCapability("name", "Bstack-[Java] Sample Test");
RemoteWebDriver driver = new RemoteWebDriver(new URL(URL), caps);
driver.setFileDetector(new LocalFileDetector());
driver.get("https://www.fileconvoy.com/");
driver.findElement(By.id("upfile_0")).sendKeys("//local//file//path");
driver.findElement(By.id("readTermsOfUse")).click();
driver.findElement(By.name("upload_button")).submit();
JavascriptExecutor jse = (JavascriptExecutor)driver;
try {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("TopMessage")));
if(driver.findElementById("TopMessage").getText().contains("successfully uploaded")) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"File uploaded successfully\"}}");
} else {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"failed\", \"reason\": \"File upload failed\"}}");
}
}
catch(Exception e) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"failed\", \"reason\": \"File could not be uploaded in 5 seconds\"}}");
}
driver.quit();
}
}
```
Copy icon
Copy
```javascript
const webdriver = require("selenium-webdriver");
const remote = require("selenium-webdriver/remote");
// Input capabilities
const capabilities = {
"browserName": "Internet Explorer",
"browser_version": "11.0",
"os": "Windows",
"os_version": "10",
"name": "Bstack-[NodeJS] Upload Test",
"browserstack.sendKeys": "true",
"browserstack.debug": "true",
"browserstack.user": "YOUR_USERNAME",
"browserstack.key": "YOUR_ACCESS_KEY"
};
const 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"));
await filePathElement.sendKeys("//local//file//path");
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
```csharp
using System;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
IWebDriver driver;
OpenQA.Selenium.IE.InternetExplorerOptions capability = new OpenQA.Selenium.IE.InternetExplorerOptions();
capability.AddAdditionalCapability("browser", "IE", true);
capability.AddAdditionalCapability("browser_version", "11", true);
capability.AddAdditionalCapability("os", "Windows", true);
capability.AddAdditionalCapability("os_version", "10", true);
capability.AddAdditionalCapability("browserstack.sendKeys", "true", true);
capability.AddAdditionalCapability("browserstack.debug", "true", true);
capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME", true);
capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY", true);
capability.AddAdditionalCapability("name", "Bstack-[C_sharp] Sample Test", true);
driver = new RemoteWebDriver(
new Uri("https://hub-cloud.browserstack.com/wd/hub/"), capability
);
driver.Navigate().GoToUrl("https://www.fileconvoy.com");
IWebElement uploadFile = driver.FindElement(By.Id("upfile_0"));
Console.WriteLine(driver.Title);
String path = "//path//to//your//local//file"; //File path in your local machine
LocalFileDetector detector = new LocalFileDetector();
var allowsDetection = driver as IAllowsFileDetection;
if (allowsDetection != null)
{
allowsDetection.FileDetector = detector;
}
uploadFile.SendKeys(path);
driver.FindElement(By.Id("readTermsOfUse")).Click();
driver.FindElement(By.Id("upload_button")).Click();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
if (driver.FindElement(By.CssSelector("#TopMessage")).Text.Contains("successfully uploaded"))
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \"File uploaded successfully!\"}}");
}
else
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"File upload failed!\"}}");
}
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
desired_cap = {
'browser': 'Internet Explorer',
'browser_version': '11.0',
'os': 'Windows',
'os_version': '10',
'browserstack.sendKeys': 'true',
'browserstack.debug': 'true',
'name': 'Bstack-[Python] Sample Test'
}
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub',
desired_capabilities=desired_cap)
driver.get('https://www.fileconvoy.com')
driver.find_element_by_id('upfile_0').send_keys('//local//file//path')
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'
# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['browser'] = 'Internet Explorer'
caps['browser_version'] = '11.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
caps['name'] = 'Bstack-[Ruby] Sample Test'
caps['browserstack.sendKeys'] = 'true'
caps['browserstack.debug'] = 'true'
caps["javascriptEnabled"]='true' #Enabling the javascriptEnabled capability to execute javascript in the test script
driver = Selenium::WebDriver.for(:remote,
:url => "https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
:desired_capabilities => caps)
driver.file_detector = lambda do |args|
str = args.first.to_s
str if File.exist?(str)
end
driver.navigate.to "https://www.fileconvoy.com"
driver.find_element(:id, "upfile_0").send_keys("//local//file//path")
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element(:name, "upload_button").submit
sleep(5)
driver.quit
```
Copy icon
Copy
To test the file upload feature on an Android device, use these methods:
Push File , to upload files from your computer to the /data/local/tmp/<file_name>
directory on the remote BrowserStack computer
Send Keys , to upload files from the remote computer to the web app under test
The Push File method doesn’t work for testing with browsers on iOS devices.
See the following sample scripts for reference:
Selenium 4 W3C test scripts to test on Android
```java
package com.browserstack;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.net.URL;
public class UploadFile {
public static final String USERNAME = "YOUR_USERNAME";
public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "@hub.browserstack.com/wd/hub";
public static void main(String[] args) throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "chrome");
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
browserstackOptions.put("osVersion", "10.0");
browserstackOptions.put("deviceName", "Samsung Galaxy S20");
browserstackOptions.put("realMobile", "true");
browserstackOptions.put("projectName", "Upload Files");
browserstackOptions.put("buildName", "Upload_file");
capabilities.setCapability("bstack:options", browserstackOptions);
/**uploading files**/
AndroidDriver<WebElement> driver = new AndroidDriver<WebElement>(new URL(URL), capabilities);
driver.get("https://the-internet.herokuapp.com/upload");
driver.pushFile("/data/local/tmp/<file_name>", new File("<local_file_path>"));
driver.findElement(By.id("file-upload")).sendKeys("/data/local/tmp/<file_name>");
//Thread.sleep(2000);
driver.findElement(By.id("file-submit")).submit();
driver.quit();
}
}
```
Copy icon
Copy
```javascript
var wd = require('wd');
var fs = require('fs')
var assert = require('assert');
var asserters = wd.asserters;
var capabilities = {
'bstack:options' : {
"osVersion" : "10.0",
"deviceName" : "Samsung Galaxy S20",
"realMobile" : "true",
"projectName" : "Upload Files",
"buildName" : "Upload_file",
"userName" : "YOUR_USERNAME",
"accessKey" : "YOUR_ACCESS_KEY",
},
"browserName" : "chrome",
}
driver = wd.promiseRemote("https://hub.browserstack.com/wd/hub");
driver
.init(capabilities)
.then(function () {
return driver.get('https://the-internet.herokuapp.com/upload');
})
.then(function () {
let data = fs.readFileSync('<local_file_path>')
let convertedData = new Buffer.from(data, 'base64')
return driver.pushFileToDevice('/data/local/tmp/<file_name>', convertedData);
})
.then(function () {
return driver.elementById("file-upload");
})
.then(function (uploadFile) {
return uploadFile.sendKeys('/data/local/tmp/<file_name>');
})
.then(function () {
return driver.elementById("file-submit");
})
.then(function (clickSubmit) {
return clickSubmit.click();
})
.fin(function() { return driver.quit(); })
.done();
```
Copy icon
Copy
```csharp
using System;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System.Collections.Generic;
using OpenQA.Selenium;
using System.IO;
using NUnit.Framework;
namespace BrowserStack
{
public class UploadFile
{
[Test]
public void Test()
{
ChromeOptions capabilities = new ChromeOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
browserstackOptions.Add("osVersion", "10.0");
browserstackOptions.Add("deviceName", "Samsung Galaxy S20");
browserstackOptions.Add("realMobile", "true");
browserstackOptions.Add("projectName", "Upload Files");
browserstackOptions.Add("buildName", "Upload_file");
browserstackOptions.Add("userName", "YOUR_USERNAME");
browserstackOptions.Add("accessKey", "YOUR_ACCESS_KEY");
browserstackOptions.Add("browserName", "chrome");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
AndroidDriver<IWebElement> driver = new AndroidDriver<IWebElement>(
new Uri("https://hub.browserstack.com/wd/hub"), capabilities);
driver.PushFile("/data/local/tmp/<file_name>", new FileInfo("<local_file_path>"));
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
driver.FindElement(By.Id("file-upload")).SendKeys("/data/local/tmp/<file_name>");
driver.FindElement(By.Id("file-submit")).Submit();
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
import time
import os
bstack_options = {
"userName": os.getenv("BROWSERSTACK_USERNAME") or "YOUR_USERNAME",
"accessKey": os.getenv("BROWSERSTACK_ACCESS_KEY") or "YOUR_ACCESS_KEY",
"osVersion" : "10.0",
"deviceName" : "Samsung Galaxy S20",
"realMobile" : "true",
"projectName" : "Upload Files",
"buildName" : "Upload_file",
}
options = Options()
options.set_capability('bstack:options', bstack_options)
driver = webdriver.Remote(
command_executor='https://hub.browserstack.com/wd/hub',
options=options)
driver.push_file("/data/local/tmp/<file_name>", source_path="<local_file_path>")
driver.get("https://cgi-lib.berkeley.edu/ex/fup.html")
driver.switch_to.context('CHROMIUM')
element = WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.XPATH, '//input[@name="upfile"]')))
time.sleep(10)
driver.find_element(By.XPATH, '//input[@name="upfile"]').send_keys("/data/local/tmp/<file_name>")
driver.find_element(By.XPATH, '//input[@type="submit"]').click()
driver.quit()
```
Copy icon
Copy
```csharp
using System;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System.Collections.Generic;
using OpenQA.Selenium;
using System.IO;
using NUnit.Framework;
namespace BrowserStack
{
public class UploadFile
{
[Test]
public void Test()
{
ChromeOptions capabilities = new ChromeOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
browserstackOptions.Add("osVersion", "10.0");
browserstackOptions.Add("deviceName", "Samsung Galaxy S20");
browserstackOptions.Add("realMobile", "true");
browserstackOptions.Add("projectName", "Upload Files");
browserstackOptions.Add("buildName", "Upload_file");
browserstackOptions.Add("userName", "YOUR_USERNAME");
browserstackOptions.Add("accessKey", "YOUR_ACCESS_KEY");
browserstackOptions.Add("browserName", "chrome");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
AndroidDriver<IWebElement> driver = new AndroidDriver<IWebElement>(
new Uri("https://hub.browserstack.com/wd/hub"), capabilities);
driver.PushFile("/data/local/tmp/<file_name>", new FileInfo("<local_file_path>"));
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
driver.FindElement(By.Id("file-upload")).SendKeys("/data/local/tmp/<file_name>");
driver.FindElement(By.Id("file-submit")).Submit();
driver.Quit();
}
}
}
```
Copy icon
Copy
Selenium Legacy JSON test scripts to test on Android
```java
package com.browserstack;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.net.URL;
public class UploadFile {
public static final String USERNAME = "YOUR_USERNAME";
public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";
public static void main(String[] args) throws Exception {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("device", "Samsung Galaxy S9");
caps.setCapability("os_version", "8.0");
caps.setCapability("name", "upload");
caps.setCapability("build", "Upload File");
/**uploading files**/
AndroidDriver<WebElement> driver = new AndroidDriver<WebElement>(new URL(URL), caps);
driver.get("https://the-internet.herokuapp.com/upload");
driver.pushFile("/data/local/tmp/<file_name>", new File("<local_file_path>"));
driver.findElement(By.id("file-upload")).sendKeys("/data/local/tmp/<file_name>");
//Thread.sleep(2000);
driver.findElement(By.id("file-submit")).submit();
driver.quit();
}
}
```
Copy icon
Copy
```javascript
var wd = require('wd');
var fs = require('fs')
var assert = require('assert');
var asserters = wd.asserters;
desiredCaps = {
'browserstack.user' : 'YOUR_USERNAME',
'browserstack.key' : 'YOUR_ACCESS_KEY',
'build' : 'Node Push File',
'name': 'upload file',
'device' : 'Google Pixel 3',
'browserstack.debug' : true
};
driver = wd.promiseRemote("https://hub-cloud.browserstack.com/wd/hub");
driver
.init(desiredCaps)
.then(function () {
return driver.get('https://the-internet.herokuapp.com/upload');
})
.then(function () {
let data = fs.readFileSync('<local_file_path>')
let convertedData = new Buffer.from(data, 'base64')
return driver.pushFileToDevice('/data/local/tmp/<file_name>', convertedData);
})
.then(function () {
return driver.elementById("file-upload");
})
.then(function (uploadFile) {
return uploadFile.sendKeys('/data/local/tmp/<file_name>');
})
.then(function () {
return driver.elementById("file-submit");
})
.then(function (clickSubmit) {
return clickSubmit.click();
})
.fin(function() { return driver.quit(); })
.done();
```
Copy icon
Copy
```csharp
using System;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System.Collections.Generic;
using OpenQA.Selenium;
using System.IO;
using NUnit.Framework;
namespace BrowserStack
{
public class UploadFile
{
[Test]
public void Test()
{
AppiumOptions caps = new AppiumOptions();
// Set your BrowserStack access credentials
caps.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME");
caps.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY");
// Specify device and os_version
caps.AddAdditionalCapability("device", "Samsung Galaxy S10");
caps.AddAdditionalCapability("os_version", "9.0");
caps.AddAdditionalCapability("build", "Upload File - CSharp");
caps.AddAdditionalCapability("name", "upload_file");
AndroidDriver<IWebElement> driver = new AndroidDriver<IWebElement>(
new Uri("https://hub-cloud.browserstack.com/wd/hub"), caps);
driver.PushFile("/data/local/tmp/<file_name>", new FileInfo("<local_file_path>"));
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
driver.FindElement(By.Id("file-upload")).SendKeys("/data/local/tmp/<file_name>");
driver.FindElement(By.Id("file-submit")).Submit();
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import time
import os
desired_cap = {
'bstack:options' : {
"userName": os.getenv("BROWSERSTACK_USERNAME") or "YOUR_USERNAME",
"accessKey": os.getenv("BROWSERSTACK_ACCESS_KEY") or "YOUR_ACCESS_KEY",
"osVersion" : "10.0",
"deviceName" : "Samsung Galaxy S20",
"realMobile" : "true",
"projectName" : "Upload Files",
"buildName" : "Upload_file",
},
"browserName" : "chrome",
}
driver = webdriver.Remote(
command_executor='https://hub.browserstack.com/wd/hub',
desired_capabilities=desired_cap)
driver.push_file("/data/local/tmp/<file_name>", source_path="<local_file_path>")
driver.get("https://cgi-lib.berkeley.edu/ex/fup.html")
driver.switch_to.context('CHROMIUM')
element = WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.XPATH, '//input[@name="upfile"]')))
time.sleep(10)
driver.find_element(By.XPATH, '//input[@name="upfile"]').send_keys("/data/local/tmp/<file_name>")
driver.find_element(By.XPATH, '//input[@type="submit"]').click()
driver.quit()
```
Copy icon
Copy
```csharp
using System;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System.Collections.Generic;
using OpenQA.Selenium;
using System.IO;
using NUnit.Framework;
namespace BrowserStack
{
public class UploadFile
{
[Test]
public void Test()
{
AppiumOptions caps = new AppiumOptions();
// Set your BrowserStack access credentials
caps.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME");
caps.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY");
// Specify device and os_version
caps.AddAdditionalCapability("device", "Samsung Galaxy S10");
caps.AddAdditionalCapability("os_version", "9.0");
caps.AddAdditionalCapability("build", "Upload File - CSharp");
caps.AddAdditionalCapability("name", "upload_file");
AndroidDriver<IWebElement> driver = new AndroidDriver<IWebElement>(
new Uri("https://hub-cloud.browserstack.com/wd/hub"), caps);
driver.PushFile("/data/local/tmp/<file_name>", new FileInfo("<local_file_path>"));
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
driver.FindElement(By.Id("file-upload")).SendKeys("/data/local/tmp/<file_name>");
driver.FindElement(By.Id("file-submit")).Submit();
driver.Quit();
}
}
}
```
Copy icon
Copy
Preload files to the BrowserStack server
When testing on Windows and Mac computers, the Local File Detector and the Send Keys methods don’t work as expected in some cases. Also, the Push File method doesn’t work for iOS devices. For these cases, BrowserStack has the following three-step workaround:
This method works for loading media (audio, image, and video) files only. You can test the file upload feature by uploading up to 5 files.
(1) First, preload your media files to the BrowserStack server using the Upload media file REST API :
```cURL
curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" -X POST "https://api-cloud.browserstack.com/automate/upload-media" -F "file=@/path/to/app/file/test.jpg"
```
Copy icon
Copy
BrowserStack returns a media_url
(hash ID) of each file that you upload:
```json
{
"media_url": "media://90c7a8h8dc82308108734e9a46c24d8f01de12881"
}
```
Copy icon
Copy
(2) Next, in your test script, specify the media_url
for each file using the uploadMedia
capability for the W3C protocol and browserstack.uploadMedia
for the JSON wire protocol:
Capability
Description
Values
uploadMedia
Set this capability if you want to use your uploaded images, videos, or audios in the test. Upload your media files to BrowserStack servers using REST API. Use the media_url
value returned as a result of the upload request to set this capability.
The media_url returned on successful upload. Example: ["media://hashedid", "media://hashedid"]
Capability
Description
Values
browserstack.uploadMedia
Set this capability if you want to use your uploaded images, videos, or audio in the test. Upload your media files to BrowserStack servers using REST API. Use the media_url
value returned as a result of the upload request to set this capability.
The media_url returned on successful upload. Example: ["media://hashedid", "media://hashedid"]
```java
MutableCapabilities capabilities = new MutableCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
browserstackOptions.put("uploadMedia", "media://21d66a8a0471097bbf5789330129e9ab97e467e3","media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d");
capabilities.setCapability("bstack:options", browserstackOptions);
```
Copy icon
Copy
```javascript
var capabilities = {
'bstack:options' : {
"uploadMedia" : ['media://21d66a8a0471097bbf5789330129e9ab97e467e3','media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d']
},
}
```
Copy icon
Copy
```csharp
SafariOptions capabilities = new SafariOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
browserstackOptions.Add("uploadMedia", "media://21d66a8a0471097bbf5789330129e9ab97e467e3","media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
```
Copy icon
Copy
```python
desired_cap = {
'bstack:options' : {
"uploadMedia" : ['media://21d66a8a0471097bbf5789330129e9ab97e467e3','media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d'],
},
}
```
Copy icon
Copy
```ruby
capabilities = {
'bstack:options' => {
"uploadMedia" => ['media://21d66a8a0471097bbf5789330129e9ab97e467e3','media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d'],
},
}
```
Copy icon
Copy
```java
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability("browserstack.uploadMedia", new String[]{"media://21d66a8a0471097bbf5789330129e9ab97e467e3","media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d"});
```
Copy icon
Copy
```javascript
var capabilities = {
'browserstack.uploadMedia': ['media://21d66a8a0471097bbf5789330129e9ab97e467e3','media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d']
}
```
Copy icon
Copy
```csharp
DesiredCapabilities capability = new DesiredCapabilities();
capability.SetCapability("browserstack.uploadMedia", new[] {"media://21d66a8a0471097bbf5789330129e9ab97e467e3","media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d"});
```
Copy icon
Copy
```python
desired_cap = {
'browserstack.uploadMedia': ['media://21d66a8a0471097bbf5789330129e9ab97e467e3','media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d']
}
```
Copy icon
Copy
```ruby
desired_caps = {
'browserstack.uploadMedia': ['media://21d66a8a0471097bbf5789330129e9ab97e467e3','media://4d5f6w4h6dq19fg4nl9o5e9ab97d1s1y0i9kl2d3d']
}
```
Copy icon
Copy
At the time of the test, each specified file is uploaded from the BrowserStack server to the BrowserStack remote computer or device used for the test. The remote directory to which a file is uploaded depends on the type of file. For example, if it’s an image file, it’s uploaded to /Documents/images
on Mac and to C:\\Users\\hello\\Documents\\images\\
on Windows.
For a list of all directories where files are stored on a BrowserStack remote computer, see Test with preloaded files.
(3) Finally, specify the corresponding fully qualified <MEDIA_DIRECTORY>
location on the remote computer as the argument to the Send Keys method. The specified files on this <MEDIA_DIRECTORY>
location are uploaded during the test to check the file upload functionality. When testing on an iOS device, write your script to access Photo Library to select the file.
The following scripts show how to access a media file previously loaded to the BrowserStack server, from a BrowserStack remote computer or iOS device:
Selenium W3C test scripts for testing on desktops
```java
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("bstack:options", new JSONObject()
.put("os", "Windows")
.put("osVersion", "10")
.put("projectName", "Sample Test")
.put("buildName", "Sample_test")
.put("uploadMedia", new JSONArray().put("media://<FILE_HASHED_ID>"))
);
capabilities.setCapability("browserName", "IE");
capabilities.setCapability("browserVersion", "11.0");
WebDriver driver = new InternetExplorerDriver(new URL("https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub"), capabilities);
try {
driver.get("https://www.fileconvoy.com");
WebElement uploadElement = driver.findElement(By.id("upfile_0"));
uploadElement.sendKeys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>");
((JavascriptExecutor) driver).executeScript("document.getElementById('readTermsOfUse').click();");
driver.findElement(By.name("upload_button")).submit();
WebElement topMessage = driver.findElement(By.id("TopMessage"));
if (topMessage.getText().contains("successfully uploaded")) {
((JavascriptExecutor) driver).executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}');
} 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": "Something wrong with script"}}');
} finally {
driver.quit();
}
```
Copy icon
Copy
```javascript
const {Builder, By, Key, until} = require('selenium-webdriver');
let capabilities = {
'bstack:options': {
'os': 'Windows',
'osVersion': '10',
'projectName': 'Sample Test',
'buildName': 'Sample_test',
'uploadMedia': ['media://<FILE_HASHED_ID>']
},
'browserName': 'IE',
'browserVersion': '11.0',
};
let driver = new Builder().usingServer('https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();
try {
driver.get('https://www.fileconvoy.com');
driver.findElement(By.id('upfile_0')).sendKeys('C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>');
driver.executeScript('document.getElementById("readTermsOfUse").click();');
driver.findElement(By.name('upload_button')).submit();
if (driver.findElement(By.id('TopMessage')).getText().includes('successfully uploaded')) {
driver.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}');
} else {
driver.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}');
}
} catch (exception) {
driver.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}');
} finally {
driver.quit();
}
```
Copy icon
Copy
```csharp
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using Newtonsoft.Json;
using System;
var capabilities = new DesiredCapabilities();
capabilities.SetCapability("bstack:options", JsonConvert.SerializeObject(new
{
os = "Windows",
osVersion = "10",
projectName = "Sample Test",
buildName = "Sample_test",
uploadMedia = new[] { "media://<FILE_HASHED_ID>" }
}));
capabilities.SetCapability("browserName", "IE");
capabilities.SetCapability("browserVersion", "11.0");
IWebDriver driver = new RemoteWebDriver(new Uri("https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub"), capabilities);
try
{
driver.Navigate().GoToUrl("https://www.fileconvoy.com");
IWebElement uploadElement = driver.FindElement(By.Id("upfile_0"));
uploadElement.SendKeys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>");
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript("document.getElementById('readTermsOfUse').click();");
driver.FindElement(By.Name("upload_button")).Submit();
IWebElement topMessage = driver.FindElement(By.Id("TopMessage"));
if (topMessage.Text.Contains("successfully uploaded"))
{
jse.ExecuteScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}');
}
else
{
jse.ExecuteScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}');
}
}
catch (Exception e)
{
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}');
}
finally
{
driver.Quit();
}
```
Copy icon
Copy
```python
from selenium import webdriver
capabilities = {
'bstack:options': {
'os': 'Windows',
'osVersion': '10',
'projectName': 'Sample Test',
'buildName': 'Sample_test',
'uploadMedia': ['media://<FILE_HASHED_ID>']
},
'browserName': 'IE',
'browserVersion': '11.0',
}
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub',
desired_capabilities=capabilities
)
try:
driver.get("https://www.fileconvoy.com")
driver.find_element_by_id("upfile_0").send_keys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>")
driver.execute_script("document.getElementById('readTermsOfUse').click();")
driver.find_element_by_name("upload_button").submit()
if "successfully uploaded" in driver.find_element_by_id("TopMessage").text:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}')
else:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}')
except:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}')
finally:
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'selenium-webdriver'
# Input capabilities
capabilities = {
'bstack:options' => {
"os" => "Windows",
"osVersion" => "10",
"projectName" => "Sample Test",
"buildName" => "Sample_test",
"uploadMedia" => ["media://<FILE_HASHED_ID>"]
},
"browserName" => "IE",
"browserVersion" => "11.0",
}
begin
driver = Selenium::WebDriver.for(
:remote,
:url => "https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub",
:capabilities => capabilities
)
driver.navigate.to "https://www.fileconvoy.com"
driver.find_element(:id, "upfile_0").send_keys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>") #File path in remote machine
# MEDIA_FOLDER will be depended on file type of uploadMedia passed, values can be "video", "images", "audio"
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element(:name, "upload_button").submit
if driver.find_element(:id, 'TopMessage').text.include? 'successfully uploaded'
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}')
else
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}')
end
rescue => exception
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}')
ensure
driver.quit
end
```
Copy icon
Copy
Selenium W3C test scripts for testing on Mac
```java
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("bstack:options", new JSONObject()
.put("os", "OS X")
.put("osVersion", "Big Sur")
.put("projectName", "Sample Test")
.put("buildName", "Sample_test")
.put("uploadMedia", new JSONArray().put("media://<FILE_HASHED_ID>"))
);
capabilities.setCapability("browserName", "IE");
capabilities.setCapability("browserVersion", "11.0");
WebDriver driver = new InternetExplorerDriver(new URL("https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub"), capabilities);
try {
driver.get("https://www.fileconvoy.com");
WebElement uploadElement = driver.findElement(By.id("upfile_0"));
uploadElement.sendKeys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>");
((JavascriptExecutor) driver).executeScript("document.getElementById('readTermsOfUse').click();");
driver.findElement(By.name("upload_button")).submit();
WebElement topMessage = driver.findElement(By.id("TopMessage"));
if (topMessage.getText().contains("successfully uploaded")) {
((JavascriptExecutor) driver).executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}');
} 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": "Something wrong with script"}}');
} finally {
driver.quit();
}
```
Copy icon
Copy
```javascript
const {Builder, By, Key, until} = require('selenium-webdriver');
let capabilities = {
'bstack:options': {
'os': 'OS X',
'osVersion': 'Big Sur',
'projectName': 'Sample Test',
'buildName': 'Sample_test',
'uploadMedia': ['media://<FILE_HASHED_ID>']
},
'browserName': 'IE',
'browserVersion': '11.0',
};
let driver = new Builder().usingServer('https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();
try {
driver.get('https://www.fileconvoy.com');
driver.findElement(By.id('upfile_0')).sendKeys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>");
driver.executeScript('document.getElementById("readTermsOfUse").click();');
driver.findElement(By.name('upload_button')).submit();
if (driver.findElement(By.id('TopMessage')).getText().includes('successfully uploaded')) {
driver.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}');
} else {
driver.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}');
}
} catch (exception) {
driver.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}');
} finally {
driver.quit();
}
```
Copy icon
Copy
```csharp
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using Newtonsoft.Json;
using System;
var capabilities = new DesiredCapabilities();
capabilities.SetCapability("bstack:options", JsonConvert.SerializeObject(new
{
os = "OS X",
osVersion = "Big Sur",
projectName = "Sample Test",
buildName = "Sample_test",
uploadMedia = new[] { "media://<FILE_HASHED_ID>" }
}));
capabilities.SetCapability("browserName", "IE");
capabilities.SetCapability("browserVersion", "11.0");
IWebDriver driver = new RemoteWebDriver(new Uri("https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub"), capabilities);
try
{
driver.Navigate().GoToUrl("https://www.fileconvoy.com");
IWebElement uploadElement = driver.FindElement(By.Id("upfile_0"));
uploadElement.SendKeys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>");
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript("document.getElementById('readTermsOfUse').click();");
driver.FindElement(By.Name("upload_button")).Submit();
IWebElement topMessage = driver.FindElement(By.Id("TopMessage"));
if (topMessage.Text.Contains("successfully uploaded"))
{
jse.ExecuteScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}');
}
else
{
jse.ExecuteScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}');
}
}
catch (Exception e)
{
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}');
}
finally
{
driver.Quit();
}
```
Copy icon
Copy
```python
from selenium import webdriver
capabilities = {
'bstack:options': {
'os': 'OS X',
'osVersion': 'Big Sur',
'projectName': 'Sample Test',
'buildName': 'Sample_test',
'uploadMedia': ['media://<FILE_HASHED_ID>']
},
'browserName': 'IE',
'browserVersion': '11.0',
}
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub',
desired_capabilities=capabilities
)
try:
driver.get("https://www.fileconvoy.com")
driver.find_element_by_id("upfile_0").send_keys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>")
driver.execute_script("document.getElementById('readTermsOfUse').click();")
driver.find_element_by_name("upload_button").submit()
if "successfully uploaded" in driver.find_element_by_id("TopMessage").text:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}')
else:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}')
except:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}')
finally:
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'selenium-webdriver'
# Input capabilities
capabilities = {
'bstack:options' => {
"os" => "OS X",
"osVersion" => "Big Sur",
"projectName" => "Sample Test",
"buildName" => "Sample_test",
"uploadMedia" => ["media://<FILE_HASHED_ID>"]
},
"browserName" => "IE",
"browserVersion" => "11.0",
}
begin
driver = Selenium::WebDriver.for(
:remote,
:url => "https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub",
:capabilities => capabilities
)
driver.navigate.to "https://www.fileconvoy.com"
driver.find_element(:id, "upfile_0").send_keys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>") #File path in remote machine
# MEDIA_FOLDER will be depended on file type of uploadMedia passed, values can be "video", "images", "audio"
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element(:name, "upload_button").submit
if driver.find_element(:id, 'TopMessage').text.include? 'successfully uploaded'
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}')
else
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}')
end
rescue => exception
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}')
ensure
driver.quit
end
```
Copy icon
Copy
Selenium W3C test scripts for testing on iOS
```java
import java.net.URL;
import java.util.List;
import java.util.HashMap;
import java.util.Set;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import io.github.cdimascio.dotenv.Dotenv;
public class Upload extends Thread{
private static Dotenv dotenv = Dotenv.load();
public static String userName = dotenv.get("BROWSERSTACK_USERNAME");
public static String accessKey = dotenv.get("BROWSERSTACK_ACCESS_KEY");
public static void main(String args[]) throws MalformedURLException, InterruptedException {
DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
browserstackOptions.put("osVersion", "14");
browserstackOptions.put("deviceName", "iPhone 12");
browserstackOptions.put("realMobile", "true");
browserstackOptions.put("projectName", "Sample Test");
browserstackOptions.put("buildName", "Sample Build");
browserstackOptions.put("debug", "true");
capabilities.setCapability("bstack:options", browserstackOptions);
capabilities.setCapability("appium:nativeWebTap",true);
IOSDriver<IOSElement> driver = new IOSDriver<IOSElement>(new URL("https://"+userName+":"+accessKey+"@hub-cloud.browserstack.com/wd/hub"), capabilities);
driver.get("https://the-internet.herokuapp.com/upload");
Thread.sleep(5000);
driver.findElement(By.id("file-upload")).click();
driver.context("NATIVE_APP");
driver.findElement(By.name("Photo Library")).click();
Thread.sleep(5000);
List list = driver.findElements(By.className("XCUIElementTypeImage"));
((IOSElement) list.get(0)).click();
Thread.sleep(5000);
driver.findElement(By.name("Choose")).click();
Set<String> contextName = driver.getContextHandles();
driver.context(contextName.toArray()[1].toString());
driver.findElement(By.id("file-submit")).click();
driver.quit();
}
}
```
Copy icon
Copy
```javascript
const { remote, By } = require('webdriverio');
require('dotenv').config();
const username = process.env.BROWSERSTACK_USERNAME;
const accessKey = process.env.BROWSERSTACK_ACCESS_KEY;
const desiredCapabilities = {
'bstack:options': {
osVersion: '14',
deviceName: 'iPhone 12',
realMobile: 'true',
projectName: 'Sample Test',
buildName: 'Sample_test',
debug: 'true',
userName: username,
accessKey: accessKey
}
};
const options = {
hostname: 'hub.browserstack.com',
port: 443,
protocol: 'https'
};
const capabilities = {
'appium:nativeWebTap': true,
'appium:automationName': 'XCUITest',
'bstack:options': desiredCapabilities['bstack:options']
};
async function runTest() {
const driver = await remote({
...options,
capabilities,
path: '/wd/hub'
});
try {
await driver.url('https://the-internet.herokuapp.com/upload');
await driver.pause(10000);
const fileUpload = await driver.$('#file-upload'); //find by id
await fileUpload.click();
await driver.pause(5000);
await driver.switchContext('NATIVE_APP');
const photoLibraryButton = await driver.$('[name="Photo Library"]');
await photoLibraryButton.click();
await driver.pause(5000);
const elements = await driver.$$('//XCUIElementTypeImage');
await elements[0].click(); // 1 represents the second element from the list of 9 preloaded images and videos
await driver.pause(10000);
const chooseButton = await driver.$('[name="Choose"]');
await chooseButton.click();
await driver.pause(5000);
const contexts = await driver.getContexts();
await driver.switchContext(contexts[1]);
await driver.pause(5000);
const fileSubmitButton = await driver.$('#file-submit');
await fileSubmitButton.click();
} finally {
await driver.deleteSession();
}
}
runTest();
```
Copy icon
Copy
```csharp
using System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.iOS;
using dotenv.net;
namespace SampleTests
{
class UploadFile
{
static void Main(string[] args)
{
AppiumDriver driver;
AppiumOptions capabilities = new AppiumOptions();
Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
browserstackOptions.Add("osVersion", "14");
browserstackOptions.Add("deviceName", "iPhone 12");
browserstackOptions.Add("realMobile", "true");
browserstackOptions.Add("projectName", "Sample Test");
browserstackOptions.Add("buildName", "Sample_test");
browserstackOptions.Add("debug", "true");
capabilities.AddAdditionalAppiumOption("bstack:options", browserstackOptions);
capabilities.AutomationName = "XCUITest";
capabilities.AddAdditionalAppiumOption("appium:nativeWebTap", true);
DotEnv.Load();
string? userName = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME");
string? accessKey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY");
Uri serverUri = new Uri($"https://{userName}:{accessKey}@hub-cloud.browserstack.com/wd/hub/");
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
Thread.Sleep(10000);
driver.FindElement(By.Id("file-upload")).Click();
driver.Context = "NATIVE_APP";
driver.FindElement(By.XPath("//XCUIElementTypeButton[@name='Photo Library']")).Click();
Thread.Sleep(5000);
IWebElement element = driver.FindElements(By.XPath("//XCUIElementTypeImage"))[0];
element.Click();
Thread.Sleep(5000);
driver.FindElement(By.XPath("//XCUIElementTypeButton[@name='Choose']")).Click();
Thread.Sleep(5000);
driver.Context = driver.Contexts[1];
Console.WriteLine(driver.Title);
driver.FindElement(By.Id("file-submit")).Click();
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common import action_chains, keys
from time import sleep
from selenium.webdriver.common.by import By
from appium.options.ios import XCUITestOptions
from dotenv import load_dotenv
import os
load_dotenv()
user_name = os.environ.get('BROWSERSTACK_USERNAME')
access_key = os.environ.get('BROWSERSTACK_ACCESS_KEY')
desired_cap = {
'bstack:options' : {
"osVersion" : "14",
"deviceName" : "iPhone 12",
"realMobile" : "true",
"projectName" : "Sample Test",
"buildName" : "Sample_test",
"debug" : "true",
"userName": user_name,
"accessKey": access_key
},
}
options = XCUITestOptions()
options.set_capability('appium:nativeWebTap', True)
options.set_capability('appium:automationName', 'XCUITest')
options.set_capability('bstack:options', desired_cap['bstack:options'])
driver = webdriver.Remote(
command_executor='https://hub.browserstack.com/wd/hub',
options=options)
driver.get("https://the-internet.herokuapp.com/upload")
sleep(10)
driver.find_element(By.ID, 'file-upload').click()
driver.switch_to.context('NATIVE_APP')
driver.find_element(By.NAME, 'Photo Library').click()
sleep(5)
elements = driver.find_elements(By.CLASS_NAME, "XCUIElementTypeImage")
elements[0].click() # 1 represents second element from the list of 9 preloaded images and videos
sleep(10)
driver.find_element(By.NAME, 'Choose').click()
sleep(10)
driver.switch_to.context(driver.contexts[1])
driver.find_element(By.ID, "file-submit").click()
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'appium_lib'
require 'dotenv'
Dotenv.load
user_name = ENV['BROWSERSTACK_USERNAME']
access_key = ENV['BROWSERSTACK_ACCESS_KEY']
# Input capabilities
capabilities = {
'bstack:options' => {
"osVersion" => "14",
"deviceName" => "iPhone 12",
"realMobile" => "true",
"projectName" => "Sample Test",
"buildName" => "Sample_test",
"debug" => "true",
},
"appium:nativeWebTap" => true
}
appium_driver = Appium::Driver.new({'caps' => capabilities,'appium_lib' => {:server_url => "https://#{user_name}:#{access_key}@hub-cloud.browserstack.com/wd/hub"}}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://the-internet.herokuapp.com/upload"
sleep(5)
driver.find_element(xpath: "//*[@id='file-upload']").click
driver.set_context('NATIVE_APP')
sleep(10)
driver.find_element(name: "Photo Library").click
sleep(5)
elements=driver.find_elements(:class_name,"XCUIElementTypeImage")
elements[0].click
driver.find_element(name: "Choose").click
contexts = driver.available_contexts
driver.set_context contexts[1]
driver.find_element(:id,"file-submit").click()
driver.quit()
```
Copy icon
Copy
Selenium Legacy JSON test scripts for testing on desktops
```java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
public class FileUpload {
public static void main(String[] args) throws Exception {
ChromeOptions caps = new ChromeOptions();
caps.setCapability("os", "Windows");
caps.setCapability("os_version", "10");
caps.setCapability("browser", "chrome");
caps.setCapability("browser_version", "latest");
caps.setCapability("browserstack.local", "false");
caps.setCapability("browserstack.uploadMedia", "media://<FILE_HASHED_ID>");
WebDriver driver = new RemoteWebDriver(new URL("https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub"), caps);
try {
driver.get("https://www.fileconvoy.com");
driver.findElement(By.id("upfile_0")).sendKeys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>"); //File path in remote machine
// MEDIA_FOLDER will be depended on file type of uploadMedia passed, values can be "video", "images", "audio"
driver.executeScript("document.getElementById('readTermsOfUse').click();");
driver.findElement(By.name("upload_button")).submit();
String ele = driver.findElement(By.id("TopMessage")).getText();
if (ele.contains("successfully uploaded")) {
driver.executeScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'passed','reason': 'File upload successful'}}");
} else {
driver.executeScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'failed','reason': 'File upload failed'}}");
}
} catch (Exception e) {
driver.executeScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'failed','reason': 'Something wrong with script'}}");
} finally {
driver.quit();
}
}
}
```
Copy icon
Copy
```javascript
const {Builder, By, Key, until} = require('selenium-webdriver');
async function example() {
const cap = {
'browserName': 'chrome',
'browserstack.local':'false',
'browserstack.uploadMedia':["media://<FILE_HASHED_ID>"],
'browser_version': 'latest',
'os':'Windows',
'os_version':'10'
}
let driver = await new Builder().usingServer('https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub').
withCapabilities(cap).build();
try {
await driver.get('https://www.fileconvoy.com');
await driver.findElement(By.id('upfile_0')).sendKeys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>");
await driver.executeScript("document.getElementById('readTermsOfUse').click();");
await driver.findElement(By.name("upload_button")).submit();
let ele = await driver.findElement(By.id("TopMessage")).getText();
if (ele.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 (error) {
await driver.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}');
} finally {
await driver.quit();
}
}
example();
```
Copy icon
Copy
```csharp
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
class FileUpload
{
static void Main(string[] args)
{
var caps = new DesiredCapabilities();
caps.SetCapability("os", "Windows");
caps.SetCapability("os_version", "10");
caps.SetCapability("browser", "chrome");
caps.SetCapability("browser_version", "latest");
caps.SetCapability("browserstack.local", "false");
caps.SetCapability("browserstack.uploadMedia", "media://<FILE_HASHED_ID>");
IWebDriver driver = new RemoteWebDriver(new Uri("https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub"), caps);
try
{
driver.Navigate().GoToUrl("https://www.fileconvoy.com");
driver.FindElement(By.Id("upfile_0")).SendKeys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>");
driver.ExecuteScript("document.getElementById('readTermsOfUse').click();");
driver.FindElement(By.Name("upload_button")).Submit();
string ele = driver.FindElement(By.Id("TopMessage")).Text;
if (ele.Contains("successfully uploaded"))
{
driver.ExecuteScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'passed','reason': 'File upload successful'}}");
}
else
{
driver.ExecuteScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'failed','reason': 'File upload failed'}}");
}
}
catch (Exception e)
{
driver.ExecuteScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'failed','reason': 'Something wrong with script'}}");
}
finally
{
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from selenium import webdriver
# Input capabilities
caps = {
"os": "Windows",
"os_version": "10",
"browser": "chrome",
"browser_version": "latest",
"browserstack.local": "false",
"browserstack.uploadMedia": ["media://<FILE_HASHED_ID>"],
}
try:
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub',
desired_capabilities=caps
)
driver.get("https://www.fileconvoy.com")
driver.find_element_by_id("upfile_0").send_keys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>") #File path in remote machine
# MEDIA_FOLDER will be depended on file type of uploadMedia passed, values can be "video", "images", "audio"
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element_by_name("upload_button").submit()
if "successfully uploaded" in driver.find_element_by_id("TopMessage").text:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}')
else:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}')
except Exception as e:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}')
finally:
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'selenium-webdriver'
# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps["os"] = "Windows"
caps["os_version"] = "10"
caps["browser"] = "chrome"
caps["browser_version"] = "latest"
caps["browserstack.local"] = "false"
caps["browserstack.uploadMedia"] = ["media://<FILE_HASHED_ID>"]
begin
driver = Selenium::WebDriver.for(
:remote,
:url => "https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub",
:capabilities => caps
)
driver.navigate.to "https://www.fileconvoy.com"
driver.find_element(:id, "upfile_0").send_keys("C:\\Users\\hello\\Documents\\<MEDIA_FOLDER>\\<IMAGE_NAME>.<IMAGE_EXT>") #File path in remote machine
# MEDIA_FOLDER will be depended on file type of uploadMedia passed, values can be "video", "images", "audio"
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element(:name, "upload_button").submit
if driver.find_element(:id, 'TopMessage').text.include? 'successfully uploaded'
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}')
else
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}')
end
rescue => exception
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}')
ensure
driver.quit
end
```
Copy icon
Copy
Selenium Legacy JSON test scripts for testing on Mac
```java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
public class FileUpload {
public static void main(String[] args) throws Exception {
ChromeOptions caps = new ChromeOptions();
caps.setCapability("os", "OS X");
caps.setCapability("os_version", "Big Sur");
caps.setCapability("browser", "chrome");
caps.setCapability("browser_version", "latest");
caps.setCapability("browserstack.local", "false");
caps.setCapability("browserstack.uploadMedia", "media://<FILE_HASHED_ID>");
WebDriver driver = new RemoteWebDriver(new URL("https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub"), caps);
try {
driver.get("https://www.fileconvoy.com");
driver.findElement(By.id("upfile_0")).sendKeys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>"); //File path in remote machine
// MEDIA_FOLDER will be depended on file type of uploadMedia passed, values can be "video", "images", "audio"
driver.executeScript("document.getElementById('readTermsOfUse').click();");
driver.findElement(By.name("upload_button")).submit();
String ele = driver.findElement(By.id("TopMessage")).getText();
if (ele.contains("successfully uploaded")) {
driver.executeScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'passed','reason': 'File upload successful'}}");
} else {
driver.executeScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'failed','reason': 'File upload failed'}}");
}
} catch (Exception e) {
driver.executeScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'failed','reason': 'Something wrong with script'}}");
} finally {
driver.quit();
}
}
}
```
Copy icon
Copy
```javascript
const {Builder, By, Key, until} = require('selenium-webdriver');
async function example() {
const cap = {
'browserName': 'chrome',
'browserstack.local':'false',
'browserstack.uploadMedia':["media://<FILE_HASHED_ID>"],
'browser_version': 'latest',
'os':'OS X',
'os_version':'Big Sur'
}
let driver = await new Builder().usingServer('https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub').
withCapabilities(cap).build();
try {
await driver.get('https://www.fileconvoy.com');
await driver.findElement(By.id('upfile_0')).sendKeys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>");
await driver.executeScript("document.getElementById('readTermsOfUse').click();");
await driver.findElement(By.name("upload_button")).submit();
let ele = await driver.findElement(By.id("TopMessage")).getText();
if (ele.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 (error) {
await driver.executeScript('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}');
} finally {
await driver.quit();
}
}
example();
```
Copy icon
Copy
```csharp
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
class FileUpload
{
static void Main(string[] args)
{
var caps = new DesiredCapabilities();
caps.SetCapability("os", "OS X");
caps.SetCapability("os_version", "Big Sur");
caps.SetCapability("browser", "chrome");
caps.SetCapability("browser_version", "latest");
caps.SetCapability("browserstack.local", "false");
caps.SetCapability("browserstack.uploadMedia", "media://<FILE_HASHED_ID>");
IWebDriver driver = new RemoteWebDriver(new Uri("https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub"), caps);
try
{
driver.Navigate().GoToUrl("https://www.fileconvoy.com");
driver.FindElement(By.Id("upfile_0")).SendKeys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>");
driver.ExecuteScript("document.getElementById('readTermsOfUse').click();");
driver.FindElement(By.Name("upload_button")).Submit();
string ele = driver.FindElement(By.Id("TopMessage")).Text;
if (ele.Contains("successfully uploaded"))
{
driver.ExecuteScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'passed','reason': 'File upload successful'}}");
}
else
{
driver.ExecuteScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'failed','reason': 'File upload failed'}}");
}
}
catch (Exception e)
{
driver.ExecuteScript("browserstack_executor: {'action': 'setSessionStatus', 'arguments': {'status':'failed','reason': 'Something wrong with script'}}");
}
finally
{
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from selenium import webdriver
# Input capabilities
caps = {
"os": "OS X",
"os_version": "Big Sur",
"browser": "chrome",
"browser_version": "latest",
"browserstack.local": "false",
"browserstack.uploadMedia": ["media://<FILE_HASHED_ID>"],
}
try:
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub',
desired_capabilities=caps
)
driver.get("https://www.fileconvoy.com")
driver.find_element_by_id("upfile_0").send_keys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>") #File path in remote machine
# MEDIA_FOLDER will be depended on file type of uploadMedia passed, values can be "video", "images", "audio"
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element_by_name("upload_button").submit()
if "successfully uploaded" in driver.find_element_by_id("TopMessage").text:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}')
else:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}')
except Exception as e:
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}')
finally:
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'selenium-webdriver'
# Input capabilities
caps = Selenium::WebDriver::Remote::Capabilities.new
caps["os"] = "OS X"
caps["os_version"] = "Big Sur"
caps["browser"] = "chrome"
caps["browser_version"] = "latest"
caps["browserstack.local"] = "false"
caps["browserstack.uploadMedia"] = ["media://<FILE_HASHED_ID>"]
begin
driver = Selenium::WebDriver.for(
:remote,
:url => "https://YOUR_USERNAME:YOUR_ACCESSKEY@hub-cloud.browserstack.com/wd/hub",
:capabilities => caps
)
driver.navigate.to "https://www.fileconvoy.com"
driver.find_element(:id, "upfile_0").send_keys("/Users/test1/Documents/<MEDIA_FOLDER><IMAGE_NAME>.<IMAGE_EXT>") #File path in remote machine
# MEDIA_FOLDER will be depended on file type of uploadMedia passed, values can be "video", "images", "audio"
driver.execute_script('document.getElementById("readTermsOfUse").click();')
driver.find_element(:name, "upload_button").submit
if driver.find_element(:id, 'TopMessage').text.include? 'successfully uploaded'
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "File upload successful"}}')
else
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "File upload failed"}}')
end
rescue => exception
driver.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Something wrong with script"}}')
ensure
driver.quit
end
```
Copy icon
Copy
Selenium Legacy JSON test scripts for testing on iOS
```java
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import io.github.cdimascio.dotenv.Dotenv;
public class Upload extends Thread{
private static Dotenv dotenv = Dotenv.load();
public static String userName = dotenv.get("BROWSERSTACK_USERNAME");
public static String accessKey = dotenv.get("BROWSERSTACK_ACCESS_KEY");
public static void main(String args[]) throws MalformedURLException, InterruptedException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("device", "iPhone 12 Pro Max");
caps.setCapability("os_version", "14");
caps.setCapability("real_mobile", "true");
caps.setCapability("project", "My First Project");
caps.setCapability("build", "My First Build");
caps.setCapability("name", "Bstack-[Java] Sample Test");
caps.setCapability("nativeWebTap", "true");
IOSDriver<IOSElement> driver = new IOSDriver<IOSElement>(new URL("https://"+userName+":"+accessKey+"@hub-cloud.browserstack.com/wd/hub"), caps);
driver.get("https://the-internet.herokuapp.com/upload");
Thread.sleep(5000);
driver.findElement(By.id("file-upload")).click();
driver.context("NATIVE_APP");
driver.findElement(By.name("Photo Library")).click();
Thread.sleep(5000);
List list = driver.findElements(By.className("XCUIElementTypeImage"));
((IOSElement) list.get(0)).click();
Thread.sleep(5000);
driver.findElement(By.name("Choose")).click();
Set<String> contextName = driver.getContextHandles();
driver.context(contextName.toArray()[1].toString());
driver.findElement(By.id("file-submit")).click();
driver.quit();
}
}
```
Copy icon
Copy
```javascript
var wd = require('wd');
require('dotenv').config();
// Input capabilities
const capabilities = {
'device' : 'iPhone 12',
'realMobile' : 'true',
'os_version' : '14.0',
'browserName' : 'iPhone',
'name': 'BStack-[NodeJS] Sample Test',
'build': 'BStack Build Number 1',
"nativeWebTap":true
}
const username = process.env.BROWSERSTACK_USERNAME;
const accessKey = process.env.BROWSERSTACK_ACCESS_KEY;
async function runTestWithCaps () {
let driver = wd.promiseRemote(`https://${username}:${accessKey}@hub-cloud.browserstack.com/wd/hub`);
await driver.init(capabilities);
await driver.get("https://the-internet.herokuapp.com/upload")
await new Promise(r => setTimeout(r, 2000));
element = await driver.waitForElementById('file-upload')
await element.click()
await driver.context('NATIVE_APP')
element = await driver.waitForElementByName('Photo Library')
await element.click()
await new Promise(r => setTimeout(r, 2000));
element = await driver.elementsByClassName('XCUIElementTypeImage')
await element[0].click()
await new Promise(r => setTimeout(r, 5000));
element = await driver.waitForElementByName('Choose')
await element.click()
await new Promise(r => setTimeout(r, 10000));
contexts = await driver.contexts();
await driver.context(contexts[1])
element = await driver.waitForElementById("file-submit")
await element.click()
await driver.quit();
}
runTestWithCaps();
```
Copy icon
Copy
```csharp
using System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.iOS;
using dotenv.net;
namespace SampleTests
{
class UploadFile
{
static void Main(string[] args)
{
AppiumDriver<IWebElement> driver;
AppiumOptions capability = new AppiumOptions();
capability.AddAdditionalCapability("browserName", "iPhone");
capability.AddAdditionalCapability("device", "iPhone 12");
capability.AddAdditionalCapability("realMobile", "true");
capability.AddAdditionalCapability("os_version", "14");
capability.AddAdditionalCapability("browserstack.debug", "true");
capability.AddAdditionalCapability("nativeWebTap", "true");
DotEnv.Load();
string? userName = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME");
string? accessKey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY");
Uri serverUri = new Uri($"https://{userName}:{accessKey}@hub-cloud.browserstack.com/wd/hub/");
driver = new IOSDriver<IWebElement>(serverUri, capability);
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
Thread.Sleep(10000);
driver.FindElementById("file-upload").Click();
driver.Context = "NATIVE_APP";
driver.FindElement(By.Name("Photo Library")).Click();
Thread.Sleep(5000);
IWebElement element = driver.FindElementsByClassName("XCUIElementTypeImage")[0];
element.Click();
Thread.Sleep(5000);
driver.FindElementByName("Choose").Click();
Thread.Sleep(5000);
driver.Context = driver.Contexts[1];
Console.WriteLine(driver.Title);
driver.FindElementById("file-submit").Click();
driver.Quit();
}
}
}
```
Copy icon
Copy
```python
from appium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from dotenv import load_dotenv
import os
load_dotenv()
user_name = os.environ.get('BROWSERSTACK_USERNAME')
access_key = os.environ.get('BROWSERSTACK_ACCESS_KEY')
desired_cap = {
"device": "iPhone 12",
"os_version": "14",
"real_mobile": "true",
"browserstack.debug": "true",
'name': 'Sample Test',
'build': 'Sample_test',
"nativeWebTap": True,
'appium:automationName': 'XCUITest',
}
driver = webdriver.Remote(command_executor=f'https://{user_name}:{access_key}@hub-cloud.browserstack.com/wd/hub', desired_capabilities=desired_cap)
driver.get("https://the-internet.herokuapp.com/upload")
sleep(10)
driver.find_element_by_id('file-upload').click()
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name('Photo Library').click()
sleep(5)
elements = driver.find_elements_by_class_name("XCUIElementTypeImage")
elements[0].click() # 1 represents second element from the list of 9 preloaded images and videos
sleep(5)
driver.find_element_by_name("Choose").click()
sleep(10)
driver.switch_to.context(driver.contexts[1])
driver.find_element_by_id("file-submit").click()
driver.quit()
```
Copy icon
Copy
```ruby
require 'rubygems'
require 'appium_lib'
require 'dotenv'
Dotenv.load
user_name = ENV['BROWSERSTACK_USERNAME']
access_key = ENV['BROWSERSTACK_ACCESS_KEY']
# Input capabilities
caps = {}
caps['device'] = 'iPhone 12'
caps['os_version'] = '14'
caps['realMobile'] = 'true'
caps['name'] = 'BStack-[Ruby] Sample Test' # test name
caps['build'] = 'BStack Build Number 1' # CI/CD job or build name
caps['nativeWebTap'] = 'true'
caps['appium:automationName'] = 'XCUITest'
appium_driver = Appium::Driver.new({'caps' => caps,'appium_lib' => {:server_url => "https://#{user_name}:#{access_key}@hub-cloud.browserstack.com/wd/hub"}}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://the-internet.herokuapp.com/upload"
sleep(5)
driver.find_element(xpath: "//*[@id='file-upload']").click
driver.set_context('NATIVE_APP')
sleep(10)
driver.find_element(name: "Photo Library").click
sleep(5)
elements=driver.find_elements(:class_name,"XCUIElementTypeImage")
elements[0].click
sleep(5)
driver.find_element(name: "Choose").click
sleep(5)
contexts = driver.available_contexts
driver.set_context contexts[1]
driver.find_element(:id,"file-submit").click()
driver.quit()
```
Copy icon
Copy
The table below lists different types of media and non-media files that you can preload to the BrowserStack server:
OS
Max size
Allowed type
macOS
15MB
.png
, .tiff
, .tif
, .jpg
, .jpeg
, .gif
, .bmp
, .bmpf
Windows - Any supported browser
15MB
.png
, .jpg
, .jpeg
, .gif
, .svg
, .webp
, .avif
iOS
15MB
.png
, .tiff
, .tif
, .jpg
, .jpeg
, .gif
, .bmp
, .bmpf
Android
15MB
.png
, .jpg
, .jpeg
, .gif
, .bmp
, .bmpf
OS
Max size
Allowed type
macOS
50MB
.mp4
, .mov
Windows - Any supported browser
50MB
.mp4
, .webm
, .3gp
, .qt
, .qtff
, .ogg
iOS
50MB
.mp4
, .mov
Android
50MB
.mp4
, .mkv
, .3gp
, .3gpp
OS
Max size
Allowed type
macOS
15MB
.aac
, .aiff
, .mp3
, .wav
Windows
15MB
.aac
, .mp3
, .wav
iOS
15MB
.aac
, .aiff
, .mp3
, .wav
Android
15MB
.mp3
, .wav
OS
Max size
Allowed type
macOS
15MB
.zip
, .xlsx
, .xls
, .pdf
, .pnp
, .csv
, .html
, .txt
, .ppt
, .doc
, .docx
, .tar
, .rar
Windows
15MB
.zip
, .xlsx
, .xls
, .pdf
, .pnp
, .csv
, .html
, .txt
, .ppt
, .doc
, .docx
, .tar
, .rar
iOS
NA
Uploading non-media files to iOS is not supported.`
Android
NA
Uploading non-media files to Android is not supported.