40

This is a canonical question, intended to provide a comprehensive answer to many related questions

During the course of a Webdriver test, I want to upload files. However, this opens a native file picker, which Webdriver doesn't seem to support interacting with. How do I interact with it?

10 Answers 10

33

Uploading files using Webdriver

Note: this answer applies to Selenium 2. Apparently Selenium 3 changed the interface again.

Locally

If the file is on the same machine or a mapped network drive, this is actually really straightforward: You need to "type" the path to the file into the file upload control. Example:

driver = webdriver.Firefox()
element = driver.find_element_by_id("fileUpload")
element.send_keys("C:\myfile.txt")

(Code from This SO answer)

Using RemoteWebDriver

In order to enable the transfer of the file from your local machine to the remote machine so it can be uploaded, you need to set what's called a File Detector. Java example:

    driver.setFileDetector(new LocalFileDetector());
    WebElement upload = driver.findElement(By.id("myfile"));
    upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg");

(Code from, and more information located at, Sauce Labs)

  • I am getting error selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element – SIslam Mar 7 '16 at 11:52
  • 1
    @Sislam You should ask a question, the comments here aren't the right place to get help. When you do, please include the snippet of HTML you're trying to automate against, as I suspect that'll be important – Yamikuronue Mar 10 '16 at 13:07
  • 1
    @Yamikuronue driver. does not have setFileDetector for me so I guess it changed, but I don't know to what – mosaad Dec 20 '16 at 12:14
  • 1
    @mosaad My company hasn't updated to Selenium 3 yet, but I've annotated the answer and put out a bounty. Hopefully it'll get an update for Selenium 3 soon! – Yamikuronue Dec 20 '16 at 12:23
  • 2
    Yes this is valid for selenium 3 as well, i am working with selenium 3 and it's working the same old way. – Keshav Dec 28 '16 at 13:47
12

Upload a file using Robot class

This method is for handling the Windows File Upload dialog, which cannot be handled using Selenium. Please follow below steps:

  • Click on the File Upload / Choose File button, so that the File Upload dialog is displayed.

    driver.findElement(By.id("uploadbutton")).click;
    
  • Copy your file's absolute path to the clipboard

    StringSelection ss = new StringSelection("D:/Test/Test1.docx");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    
  • Paste the file's absolute path into the File name field of the File Upload dialog box

    //native key strokes for CTRL, V and ENTER keys
    Robot robot = new Robot();
    
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    
  • why forward slashes in the path D://Test//Test1.docx? – ilm Feb 16 '16 at 8:09
  • Looks like a typo. It should be '\\' or '/' – LittlePanda Feb 17 '16 at 6:39
  • if the machine is logged out, this solution doesn't work, the text is pasted into an other place instead of the file selection window. this solution is what we use at the moment, and we are seeking for a solution of this problem – elhadi dp ıpɐɥןǝ Jun 28 '18 at 14:28
11

Upload a file using AutoIT

About AutoIT:

AutoIt v3 is a freeware BASIC-like scripting language designed for automating Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks.

This method is for handling the Windows File Upload dialog, which cannot be handled using Selenium. Please follow below steps:

  • Download AutoIT
  • Open SciTE Script Editor
  • Below script is used to detect the windows file upload dialog

    WinWaitActive("File Upload") //File Upload is the dialog's title
    Send("Full path of the document") 
    Send("{ENTER}")
    
  • Save the above script file as Script.au3
  • Compile the file from SciTE Editor and you will get an Script.exe file

Steps to be followed while running the test:

  • Click on the File Upload / Choose File button, so that the File Upload dialog is displayed.

    driver.findElement(By.id("uploadbutton")).click;
    
  • Invoke the Script.exe file

    Runtime.getRuntime().exec("Script.exe");
    
  • The Script.exe file will handle the file upload
5

Uploading files using Webdriver (Locally)

I present below two ways to upload a file. The first uses Python Selenium in a special case (invisible input), the second handles a Windows Dialog Box.

Invisible input

If the input is hidden, make it visible. Here is an example (Python). The input is hidden at the bottom of the page and looks like this:

<input type="file" multiple="multiple" class="dz-hidden-input" style="visibility: hidden; position: absolute; top: 0px; left: 0px; height: 0px; width: 0px;">

Now let's see how to send the file (note the use of an absolute path):

file_input = driver.find_element_by_xpath("//input[@class = 'dz-hidden-input']")
# make the input visible:
driver.execute_script('arguments[0].style = ""; arguments[0].style.display = "block"; arguments[0].style.visibility = "visible";', file_input)
# send file:
file_input.send_keys("C:\\Users\\nicolas\\Documents\\CT\\Séance_du_Lundi_15_février.pdf")

(cf This SO answer)

Interact with Windows file upload dialog (Windows and Python only)

You can directly handle the Windows dialog box using the Pywinauto module (the window has to be visible, not hidden).

import pywinauto

def Test(Name_of_File):
    app = pywinauto.application.Application()
    mainWindow = app['Envoi du fichier'] # main windows' title
    ctrl=mainWindow['Edit'] 
    mainWindow.SetFocus()
    ctrl.ClickInput()
    ctrl.TypeKeys(Name_of_File)
    ctrlBis = mainWindow['Ouvrir'] # open file button
    ctrlBis.ClickInput()

""" example:
Test("C:\\Users\\nicolas\\Documents\\CT\\Séance_du_Lundi_7_mars.pdf")
"""

Windows' titles are inside square brackets. You can easily get them (and other windows' attributes) using tools like SWAPY.

2

If you just want to send the file to the webserver, you can do it with a headless http client, for example using the mechanize library in Ruby or Perl, or the the Request library in Python. You don't need to do everything from the browser.

An example, using python:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}
0
import win32com.client  

shell = win32com.client.Dispatch("WScript.Shell")  
shell.Sendkeys("C:\text.txt")  
shell.Sendkeys("~")  

will resolve the issue

  • 3
    Could you explain what this adds to the existing answers, particularly the accepted answer? – Kate Paulk Sep 30 '16 at 11:36
0

Yamikuronue, if you are open to using other software, you can automate file uploads with the Kantu Chromium browser (https://kantu.io), and then use the Kantu API or command line to integrate with Selenium and/or your automation tool chain. The software is free, but Windows only.

For file uploads, the command "SelectFileToUpload" is used. Kantu includes a screenshot-based script recorder that will add this command automatically to your script:

Upload script

0

AutoIT code:

ControlFocus("File Upload","","Edit1");
ControlSetText("File Upload","","Edit1","E:\test.txt");
ControlClick("File Upload","","Button1");

Selenium code:

Runtime.getRuntime().exec("C:\\Users\\sudhir\\Desktop\\sssss.exe");
0

First of all, you have to switch to new open window.

browser.switchTo().window(browser.windowHandles.last())

Then you can choose the file using this.

browser.findElement(By.id("file")).sendKeys(<Absolute path the file>/<file name with extension>)

In here, absolute path will be liked, "C:/Users/dd/Pictures".

0

One more possible approach is to use Sikuli. I have an example of file upload check here.

  • Please post a code snippet as links can go dead in the future. – LittlePanda Apr 11 '18 at 12:13

protected by Kate Paulk Mar 29 '18 at 14:15

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.