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

Note: Using ‘sendKeys’ or ‘File Upload’ for file uploads will ONLY work with //input[@type,‘file’] objects. So what do you do when an //input[@type,‘file’] object is hidden?

How-to use ‘sendKeys’ or ‘File Upload’ to upload files when the //input[@type,‘file’] is hidden. Special thanks to @Russ_Thomas for his post on using document.querySelectorAll(“input[type=file]”) for finding hidden objects; which put me onto this solution. I now do NOT have to use Robot for my file uploads; which ensures my file uploads work from within Jenkins.

  1. Open Chrome/Firefox Browser.

  2. Press F12 (Developer tools).

  3. Switch to the ‘Console’ tab.

  4. Use document.querySelectorAll("input[type=file]") to find the ‘hidden’ input type.
    For example: NodeList [input#uploadDocument.hidden-file-input].

  5. Switch to the ‘Elements’ tab & use ‘Ctrl + F’ & search for 'hidden-file-input’.
    Result: <input id="uploadDocument" name="file" type="file" class="hidden-file-input" value="">.

  6. Right-click on the object & click ‘Copy’ > ‘Copy XPath’.
    Result: //*[@id="uploadDocument"]. Note that you can also add the type=‘file’ attribute into the final attribute.

  7. Paste the copied result into the ‘Elements’ search input field & validate the object.

  8. Create a new manual ‘DocumentUpload’ object where the Attributes are //*[@id = ‘uploadDocument’ and @type = ‘file’]

  9. In the test case, use the existing ‘UploadButton’ object’ to wait for the page to load before trying to upload file(s). **If needed create a new manual ‘UploadButton’ object with the correct attributes\xpath.

See the following for ‘File Upload’ use/syntax:

For multiple file uploads see this link: Upload Multiple Files - #13 by Brandon_Hein

Use something like the following in the test case:

import org.openqa.selenium.Keys as Keys
def FileName = 'C:\\Users\\jdoe\\MyDocs\\Sample.pdf'
//Wait for the 'UploadButton' to display
WebUI.waitForElementVisible(findTestObject('ManObjects/UploadButton'), 30, FailureHandling.OPTIONAL))
WebUI.sendKeys(findTestObject('ManObjects/DocumentUpload'), FileName)


Possible XPaths for a file upload button:

(//*[@type = 'file'])
(//*[@name = 'fileUpload'])
(//*[@type = 'file' and @name = 'fileUpload])

Thank @Dave_Evers for great sharing :star_struck:

Thank you so much :smiley:
It worked.