How-to use ‘sendKeys’ or 'File Upload' to upload files

The following ‘File Upload Sample’ test case uses sendKeys to upload a test Blank.png image file.
Copy the following to any test case and run, (test objects are created in memory so no objects are needed).

import org.openqa.selenium.By as By
import org.openqa.selenium.WebDriver as WebDriver
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webui.driver.DriverFactory as DriverFactory
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import java.nio.file.Path as Path
import java.nio.file.Paths as Paths


//Loads File Upload Sample page

//Loads WebDriver
WebDriver driver = DriverFactory.getWebDriver()

/** Change 'Blank.png' to any test image file being used **/
'Sets path to the test Blank.png Uploadfile'
Path uploadFilePath = Paths.get(System.getProperty('user.home'), 'Downloads', 'Blank.png')
String upLoadFile = uploadFilePath
println('upLoadFile: ' + upLoadFile)

'Finds "Select Images" Link using by.xpath & creates object'
def selectImagesLinkXpath = '//*[@type = "file"]'
TestObject selectImagesLink = WebUI.convertWebElementToTestObject(driver.findElement(By.xpath(selectImagesLinkXpath)))
WebUI.sendKeys(selectImagesLink, upLoadFile)

'Waits for file to load'

'Finds "Upload" button using by.xpath & creates object'
def uploadBtnXpath = "//button[@type='submit'][contains(.,'Upload...')]"
TestObject uploadBtn = WebUI.convertWebElementToTestObject(driver.findElement(By.xpath(uploadBtnXpath)))

1 Like