46

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

39

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)

8
  • I am getting error selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element
    – Learner
    Commented Mar 7, 2016 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 Commented Mar 10, 2016 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
    Commented Dec 20, 2016 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! Commented Dec 20, 2016 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
    Commented Dec 28, 2016 at 13:47
16

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);
    
4
  • why forward slashes in the path D://Test//Test1.docx?
    – ilm
    Commented Feb 16, 2016 at 8:09
  • Looks like a typo. It should be '\\' or '/' Commented Feb 17, 2016 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 Commented Jun 28, 2018 at 14:28
  • Nice, this works for sites where <input type='file'> element is only created after some action and destroyed after selecting file.
    – user158037
    Commented Apr 7, 2022 at 12:19
12

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 the 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
1
7

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.

1
  • this is the only solution that works for my setup (python3.9, selenium, docker). thank you so much, you have saved my day :)))))))))))
    – fanny
    Commented Oct 19, 2020 at 14:20
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>"
  },
  ...
}
2
  • Can you add the code for uploading a file using the headless client? This is a canonical question, so we are looking for all the ways one can upload a file using Selenium Webdriver. Commented May 6, 2015 at 6:58
  • This is a good example specifically with the Requests library in Python: docs.python-requests.org/en/latest/user/quickstart/…
    – user1780
    Commented May 8, 2015 at 20:33
1

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
import win32com.client  

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

will resolve the issue

1
  • 3
    Could you explain what this adds to the existing answers, particularly the accepted answer?
    – Kate Paulk
    Commented Sep 30, 2016 at 11:36
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");
1
  • I tried everything to interact with a Microsoft Windows 10 file upload dialog and the ONLY thing that worked was doing it via AutoIt.
    – Sulteric
    Commented Sep 9, 2021 at 18:17
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
0

Uploading file through Selenium Webdriver can be done through following steps:

Step 1:- Set the path of chromeDriver exe file:

System.setProperty("webdriver.chrome.driver",”./driver/chromedriver.exe");

Step 2:- Create an object of ChromeDriver Class :

WebDriver driver = new ChromeDriver();

Here we are doing upcasting, converting subclass object into Super Type.

Step 3:- Navigate to the web page where you have to upload the file:-

driver. navigate.to ("pass the URL of the page");

Now you have to find the upload button on the web page, use any locator(XPath, id or class name, etc..) to find that button and click on it.

WebElement uploadButton = driver.findElement(By.id("uploadBTN"));

uploadButton.click();

Step 4:- Now Enter the path of the file which you have to upload on WebPage:

WebElement uploadTextField = driver.findElement(By.id("uploadTextField"));

uploadTextField.sendKeys("D:\Screenshot_1.png”);

we are passing the path of .png file to upload on the web page.

Wait till the file is uploading on the page after successfully load the file click on submit button.

driver.findElement(By.name("submitBTN")).submit();

Once you run this script, you will be able to upload the file effectively and get a confirmation message (Your file is uploaded and unpacked).

I hope the above steps would have given you a perspective to handle file upload using Selenium WebDriver, in your Selenium projects. If you have a unique idea or perspective to work with the file uploads, then please let us know.

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