Skip to main content
No Result Found

Test the file upload functionality

Learn how to test the file upload functionality using BrowserStack Automate TurboScale.

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.

This feature is supported only for tests running with Selenium and Playwright framework.

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

  • Files downloaded in the same Automate TurboScale session
  • Files from your computer

Suppose your test includes downloading a file from the web. This file is downloaded to the following location on the BrowserStack remote computer:

Downloading a file from the web considerably slows down the execution of your test.

Copy icon Copy
C:\\opt\\selenium
Copy icon Copy
/opt/selenium

Within the same Automate TurboScale session, the file is available in later test steps. As a result, you can use the downloaded file to test your file upload feature.

When testing, 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:

  • 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://hub-ft.browserstack.com/wd/hub";
  public static void main(String[] args) throws Exception {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("browserName", "Chrome");
    capabilities.setCapability("browserVersion", latest);
    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
    browserstackOptions.put("os", "Windows");
    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",
		"projectName" : "Sample Test",
		"buildName" : "Sample_test",
		"userName" : "YOUR_USERNAME",
		"accessKey" : "YOUR_ACCESS_KEY",
	},
	"browserName" : "Chrome",
	"browserVersion" : latest,
}
let driver = new webdriver.Builder()
    .usingServer('https://hub-ft.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;
      ChromeOptions capabilities = new ChromeOptions();
      capabilities.BrowserVersion = latest;
      Dictionary<string, object> browserstackOptions = new Dictionary<string, object>();
      browserstackOptions.Add("os", "Windows");
      browserstackOptions.Add("projectName", "Sample Test");
      browserstackOptions.Add("buildName", "Sample_test");
      browserstackOptions.Add("userName", "YOUR_USERNAME");
      browserstackOptions.Add("accessKey", "YOUR_ACCESS_KEY");
      browserstackOptions.Add("browserName", "Chrome");
      capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
      driver = new RemoteWebDriver(
        new Uri("https://hub-ft.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",
		"projectName" : "Sample Test",
		"buildName" : "Sample_test",
        "userName" : "YOUR_USERNAME",
		"accessKey" : "YOUR_ACCESS_KEY",
	},
	"browserName" : "Chrome",
	"browserVersion" : latest,
}
options.set_capability('bstack:options', desired_cap)
driver = webdriver.Remote(
    command_executor='https://hub-ft.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",
		"projectName" => "Sample Test",
		"buildName" => "Sample_test",
		"javascriptEnabled" => "true"
		"userName" => "YOUR_USERNAME",
		"accessKey" => "YOUR_ACCESS_KEY",
	},
	"browserName" => "Chrome",
	"browserVersion" => latest,
}
driver = selenium::WebDriver.for(
    :remote,
    :url => "https://hub-ft.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

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