[java] How to handle windows file upload using Selenium WebDriver?

I have seen lots of questions and solutions on File upload using Selenium WebDriver on Stack Overflow. But none of them are working for following scenario.

Someone has given a solution as following

// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");

But still I can't find window handle. How can I work on that?

Screenshot

I am looking for a solution for the scenario above.

Please check this on any of the following websites.

http://www.uploadify.com/demos/
http://www.zamzar.com/

This question is related to java selenium file-upload selenium-webdriver webdriver

The answer is


Find the element (must be an input element with type="file" attribute) and send the path to the file.

WebElement fileInput = driver.findElement(By.id("uploadFile"));
fileInput.sendKeys("/path/to/file.jpg");

NOTE: If you're using a RemoteWebDriver, you will also have to set a file detector. The default is UselessFileDetector

WebElement fileInput = driver.findElement(By.id("uploadFile"));
driver.setFileDetector(new LocalFileDetector());
fileInput.sendKeys("/path/to/file.jpg");

        webDriver.FindElement(By.CssSelector("--cssSelector--")).Click();
        webDriver.SwitchTo().ActiveElement().SendKeys(fileName);

worked well for me. Taking another approach provided in answer above by Matt in C# .net could also work with Class name #32770 for upload box.


Using C# and Selenium this code here works for me, NOTE you will want to use a parameter to swap out "localhost" in the FindWindow call for your particular server if it is not localhost and tracking which is the newest dialog open if there is more than one dialog hanging around, but this should get you started:

    using System.Threading;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    using OpenQA.Selenium;

    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll", EntryPoint = "FindWindow")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    public static void UploadFile(this IWebDriver webDriver, string fileName)
    {
        webDriver.FindElement(By.Id("SWFUpload_0")).Click();
        var dialogHWnd = FindWindow(null, "Select file(s) to upload by localhost");
        var setFocus = SetForegroundWindow(dialogHWnd);
        if (setFocus)
        {
            Thread.Sleep(500);
            SendKeys.SendWait(fileName);
            SendKeys.SendWait("{ENTER}");
        }
    }

You have put double slash \\ for the entire absolute path to achieve this Example:- D:\\images\\Lighthouse.jpg

Steps - use sendkeys for the button having browse option(The button which will open your window box to select files) - Now click on the button which is going to upload you file

driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:\\images\\Lighthouse.jpg");  
Thread.sleep(5000);
driver.findElement(By.xpath("//button[@id='Upload']")).click();

The below one had worked for me

webDriver.findElement(By.xpath("//input[@type='file' and @name='importFile']")).sendKeys("C:/path/to/file.jpg");

There is a simpler way to solve this then what Slanec described. Hes solution works when you are using an English keyboard, if not you will have a hard time trying to "map" the key for special characters.

Instead of robot.keyPress and robot.keyRelease every single key you can use Toolkit to copy the String to the clipboard and then paste it.

    StringSelection s = new StringSelection("Path to the file");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
    Robot robot = new Robot();
    robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
    robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);
    robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
    robot.keyPress(java.awt.event.KeyEvent.VK_V);
    robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
    Thread.sleep(3000);
    robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);

Import System.Windows.Forms binary to the test solution and call the following two LOC on clicking the Upload button on the UI.

        // Send the file path and enter file path and wait.
        System.Windows.Forms.SendKeys.SendWait("complete path of the file");
        System.Windows.Forms.SendKeys.SendWait("{ENTER}");

Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.

Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");

Please use below link for further assistance: http://www.guru99.com/use-autoit-selenium.html


An alternative solution would be to write a script to automate the Open File dialog. See AutoIt.

Also, if you can't "click" the element, my workaround is generally to do this:

element.SendKeys(Keys.Enter);

Hope this helps (Even though it's an old post)


Below code works for me:

// wait for the window to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());

// switch to the file upload window
Alert alert = driver.switchTo().alert();

// enter the filename
alert.sendKeys(fileName);

// hit enter
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

// switch back
driver.switchTo().activeElement();

Double the backslashes in the path, like this:

driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");

First add the file to your project resource directory

then

public YourPage uploadFileBtnSendKeys() {
    final ClassLoader classLoader = getClass().getClassLoader();
    final File file = new File(classLoader.getResource("yourFile.whatever").getPath());
    uploadFileBtn.sendKeys(file.getPath());
    return this;
}

Walla, you will see your choosen selected file, and have skipped the file explorer window


I made use of sendkeys in shell scripting using a vbsscript file. Below is the code in vbs file,

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "C:\Demo.txt"
WshShell.SendKeys "{ENTER}"

Below is the selenium code line to run this vbs file,

driver.findElement(By.id("uploadname1")).click();
Thread.sleep(1000);
Runtime.getRuntime().exec( "wscript C:/script.vbs" );

Below code works for me :

public void test() {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.freepdfconvert.com/pdf-word");
    driver.findElement(By.id("clientUpload")).click();
    driver.switchTo()
            .activeElement()
            .sendKeys(
                    "/home/likewise-open/GLOBAL/123/Documents/filename.txt");
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    driver.findElement(By.id("convertButton"));

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java

Examples related to webdriver

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? ImportError: No module named 'selenium' how to use List<WebElement> webdriver How to get attribute of element from Selenium? Selenium Finding elements by class name in python Open web in new tab Selenium + Python When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly How can I start InternetExplorerDriver using Selenium WebDriver