62

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/
Blaszard
  • 30,954
  • 51
  • 153
  • 233
Jasmine.Olivra
  • 1,751
  • 9
  • 24
  • 37

15 Answers15

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

Hey, that's mine from somewhere :).


In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:

driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");

In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).

So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.

If not, you could try to jump to it by pressing Alt + N, at least on Windows...

If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:

driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C);        // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON);    // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH);    // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path

r.keyPress(KeyEvent.VK_ENTER);    // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);

It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).


For Flash, the only alternative I know (from this discussion) is to use the dark technique:

First, you modify the source code of you the flash application, exposing internal methods using the ActionScript's ExternalInterface API. Once exposed, these methods will be callable by JavaScript in the browser.

Second, now that JavaScript can call internal methods in your flash app, you use WebDriver to make a JavaScript call in the web page, which will then call into your flash app.

This technique is explained further in the docs of the flash-selenium project. (http://code.google.com/p/flash-selenium/), but the idea behind the technique applies just as well to WebDriver.

Community
  • 1
  • 1
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • 3
    What does "not working" mean? Why, where, with what error message? – Petr Janeček Jun 29 '12 at 08:24
  • Can't enter file path to file upload window – Jasmine.Olivra Jun 29 '12 at 08:26
  • I added a dark magic solution, too. Anyway, you're still not specific enough. Please, edit your question with what you tried and how or why it failed. – Petr Janeček Jun 29 '12 at 08:32
  • Yup. Both work for me. The `Robot` solution is obviously dependant on the keyboard layout, but I think that could be avoided somehow. – Petr Janeček Jun 29 '12 at 09:38
  • @Jasmine.Olivra Sure. Zamzar works in IE8 and FF13 on Win XP for me with the exact code I provided (I see a usual `` element there.). Uploadify with Flash enabled (when disabled, there's just a ``, too) works in IE8 and FF13 on Win XP, too, just the colon and slashes had to be done a little bit differently. Still, I managed to upload a file in both of these with the given solutions. – Petr Janeček Jun 29 '12 at 13:11
  • I used `robot.keyPress(KeyEvent.VK_ESCAPE);` to hide the dialog. Thanks for the idea. – Yevgen Yampolskiy Apr 24 '20 at 05:33
  • 1
    Side-note: Uploading multiple files is also possible via SendKeys - see https://stackoverflow.com/questions/23955430/selenium-webdriver-upload-multiple-files – Joseph238 Mar 17 '21 at 22:50
13

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"));
Emmanuel Angelo.R
  • 1,545
  • 2
  • 16
  • 24
  • 3
    This should be the answer. sendKeys() just doesn't produce any result at all, but this one works perfectly. I am using GhostDriver on Ubuntu. – Guillaume Apr 13 '15 at 14:43
5

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}");
        }
    }
kkuilla
  • 2,226
  • 3
  • 34
  • 37
Matt
  • 1,446
  • 19
  • 17
3

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" );
3

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");
Marissa Novak
  • 544
  • 3
  • 6
2

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);
  • I realise this is an old post, but like the note about the robot key press/releases, this uses a string path set at the top of the snippet `Path to the file` which is then copied to the clipboard and pasted into the field – Sandra Oct 21 '22 at 11:09
1

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

rogger2016
  • 821
  • 3
  • 11
  • 28
  • In my case i only have the option to click on button which will open the file explorer. Which element i should pass above, uploadFileBtn – Gaurav Singh Jul 06 '23 at 16:35
0

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}");
Sham
  • 830
  • 9
  • 27
0

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)

sparkyShorts
  • 630
  • 9
  • 28
0

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();
Quentin Hayot
  • 7,786
  • 6
  • 45
  • 62
0

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();
Shubham Jain
  • 16,610
  • 15
  • 78
  • 125
0

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

Anumanth
  • 25
  • 4
0
        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.

-1

The below one had worked for me

webDriver.findElement(By.xpath("//input[@type='file' and @name='importFile']")).sendKeys("C:/path/to/file.jpg");
Gautam Savaliya
  • 1,403
  • 2
  • 20
  • 31
-1

Double the backslashes in the path, like this:

driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");
Pang
  • 9,564
  • 146
  • 81
  • 122
JM Test
  • 1
  • 1