Skip to main content
Transform your testing process with: Real Device Features, Company-wide Licences, & Test Observability
No Result Found

Test the file upload functionality

Learn how to test the file upload functionality of your web app in Selenium using BrowserStack Automate.

The file upload functionality enables you to upload files to a web app. For example, submit documents for processing in various applications, upload videos or images to social media sites, upload cover letters and resumes to career sites, or attach files to emails. The functionality involves looking for a file on your computer and then uploading it. Like any web app feature, it must be tested too.

On Automate, you can test the file upload functionality of your web app using:

  • Files preloaded to the BrowserStack server
  • Files downloaded in the same Automate session
  • Files from your computer

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:

Windows 11, 10, 8.1, 8, 7
Copy icon Copy
*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
Windows XP
Copy icon Copy
C:\\Documents\ and\ Settings\\hello\\url.txt
Mac
Copy icon Copy
/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

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
Copy icon Copy
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
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
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
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
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
  • Selenium 4 W3C test scripts to test on iOS devices
Copy icon Copy
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
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
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
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
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()
  • Selenium Legacy JSON test scripts to test on desktops
Copy icon Copy
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
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
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
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
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
  • Selenium Legacy JSON test scripts to test on iOS devices
Copy icon Copy
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
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
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
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
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()

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked





Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked





Thank you for your valuable feedback!

Talk to an Expert
Download Copy Check Circle