0

I have problem with browse button and switching to file dialog. I cannot use my file path control and just send there my string with file path and file itself, as it's readonly and in fact some behind control is my input filepath.

Here's my code

driver.FindElement(By.Id("browseButton")).Click();
driver.SwitchTo().ActiveElement().SendKeys(filepath);

Above code fills my control for file path, as i can see that on UI. But my open file dialog is still opened and i do not know how to close it and submit my upload.

Michal
  • 33
  • 1
  • 5
  • @Michael Even if the file input control is readonly, easiest way to use JavaScript and modify the dom file upload instead. Please provide the html to help you with that – Saifur Apr 21 '15 at 16:57
  • so my control for upload path: `` – Michal Apr 21 '15 at 17:48

3 Answers3

2

Uploading files in Selenium can be a pain, to say the least. The real problem comes from the fact that it does not support dialog boxes such as file upload and download.

I go over this in an answer to another question, so I will just copy/paste my answer from there here. The code examples should actually be relevant in your case, since you are using C#:

Copied from previous answer on question here:

Selenium Webdriver doesn't really support this. Interacting with non-browser windows (such as native file upload dialogs and basic auth dialogs) has been a topic of much discussion on the WebDriver discussion board, but there has been little to no progress on the subject.

I have, in the past, been able to work around this by capturing the underlying request with a tool such as Fiddler2, and then just sending the request with the specified file attached as a byte blob.

If you need cookies from an authenticated session, WebDriver.magage().getCookies() should help you in that aspect.

edit: I have code for this somewhere that worked, I'll see if I can get ahold of something that you can use.

public RosterPage UploadRosterFile(String filePath){
        Face().Log("Importing Roster...");

        LoginRequest login = new LoginRequest();
        login.username = Prefs.EmailLogin;
        login.password = Prefs.PasswordLogin;
        login.rememberMe = false;
        login.forward = "";
        login.schoolId = "";

        //Set up request data
        String url = "http://www.foo.bar.com" + "/ManageRoster/UploadRoster";
        String javaScript = "return $('#seasons li.selected') .attr('data-season-id');";
        String seasonId = (String)((IJavaScriptExecutor)Driver().GetBaseDriver()).ExecuteScript(javaScript);
        javaScript = "return Foo.Bar.data.selectedTeamId;";
        String teamId = (String)((IJavaScriptExecutor)Driver().GetBaseDriver()).ExecuteScript(javaScript);

        //Send Request and parse the response into the new Driver URL
        MultipartForm form = new MultipartForm(url);
        form.SetField("teamId", teamId);
        form.SetField("seasonId", seasonId);
        form.SendFile(filePath,LoginRequest.sendLoginRequest(login));
        String response = form.ResponseText.ToString();
        String newURL = StaticBaseTestObjs.RemoveStringSubString("http://www.foo.bar.com" + response.Split('"')[1].Split('"')[0],"amp;");

        Face().Log("Navigating to URL: "+ newURL);
        Driver().GoTo(new Uri(newURL));

        return this;
    }

Where MultiPartForm is: MultiPartForm

And LoginRequest/Response: LoginRequest LoginResponse

The code above is in C#, but there are equivalent base classes in Java that will do what you need them to do to mimic this functionality.

The most important part of all of that code is the MultiPartForm.SendFile method, which is where the magic happens.

Community
  • 1
  • 1
aholt
  • 2,829
  • 2
  • 10
  • 13
1

One of the many ways to do that is to remove the disable attribute and then use typical selenium SendKeys() to accomplish that

public void test(string path)
{
    By byId = By.Id("removeAttribute");
    const string removeAttribute = @"document.getElementById('browseButton').removeAttribute('disabled');";
    ((IJavaScriptExecutor)Driver).ExecuteScript(removeAttribute);
    driver.FindElement(byId).Clear();
    driver.FindElement(byId).SendKeys(path);
}
Saifur
  • 16,081
  • 6
  • 49
  • 73
  • saifur - whilst i agree that this solves the problem (and thanks for a good example), I'm really concerned that this breaks the unit testing completely as this is not something that would happen in a real life *operational* scenario with a person and a browser. That said, the OP doesn't allude to his requirement requiring to be test compliant. hope you see my point... but good answer based on available info - +1 – jim tollan Apr 21 '15 at 19:59
  • @jimtollan Totally agree. Actually Selenium is not meant to be doing this kind of stuff. But, as all of us know Selenium cannot handle OS driving system to handle file upload. And, this is not cleaner but possibly the only way to handle this scenario with selenium – Saifur Apr 21 '15 at 20:55
1
You can use this Auto IT Script to Handle File Upload Option.

Auto IT Script for File Upload:

AutoItSetOption("WinTitleMatchMode","2") ; set the select mode to
Do
Sleep ("1000")
until WinExists("File Upload")
WinWait("File Upload")
WinActivate("File Upload")
ControlFocus("File Upload","","Edit1")
Sleep(2000)
ControlSetText("File Upload" , "", "Edit1",   $CmdLineRaw)
Sleep(2000)
ControlClick("File Upload" , "","Button1");

Build and Compile the above code and place the EXE in a path and call it when u need it.

Call this Once you click in the Browse Button.
  Process p = System.Diagnostics.Process.Start(txt_Browse.Text + "\\File Upload", DocFileName);
  p.WaitForExit();
Madhu
  • 479
  • 4
  • 10
  • may i know wat reason for downvoting it – Madhu May 04 '15 at 11:49
  • Thanks you man ! It's brillant ! I have written a better version though : http://pastebin.com/CDqQ4wdq – Jamesst20 Dec 02 '15 at 21:26
  • I didn't like your approach as it utilise a different programming language and executable's instead of C# but it seems to be the only consistent way currently to make a test work with a upload window opening up from a hidden field. unfortunately your script needed to be corrected for my language not that it was a big issue. So Thank you for your alternative Hack. – Helbo Jun 08 '18 at 07:41