English 中文(简体)
Selenium RC > how to upload file using attachFile()
原标题:

I am using Selenium RC with Junit framework. I am trying to upload a file using attachFile() method.

attachFile: (Information collected from selenium API http://release.seleniumhq.org/selenium-remote-control/1.0-beta-2/doc/java/com/thoughtworks/selenium/Selenium.html#attachFile(java.lang.String,%20java.lang.String))

void attachFile(java.lang.String fieldLocator,
            java.lang.String fileLocator)

Sets a file input (upload) field to the file listed in fileLocator

Parameters:
    fieldLocator - an element locator
    fileLocator - a URL pointing to the specified file. Before the file can be set
  in the input field (fieldLocator), Selenium RC may need to transfer the file to 
  the local machine before attaching the file in a web page form. This is common in 
  selenium grid configurations where the RC server driving the browser is not the 
  same machine that started the test. Supported Browsers: Firefox ("*chrome") only.

Can anyone please tell me how to define "fileLocator". I am not getting which URL to be specify over here. Please give me an example if possible.

最佳回答

I got solution for this, use selenium.focus method and the selenium.keyPressNative/keyReleaseNative methods.

You will need to give focus to the text box using:

selenium.focus("text box locator");

Then if your input file is C: oolsFile.txt you need to type the letters like so:

selenium.keyDownNative("16"); //SHIFT ON

selenium.keyPressNative("67"); // c shift makes it C

selenium.keyPressNative("59"); // ; Shift makes it : (you can t do colon directly)

selenium.keyUpNative("16"); // SHIFT OFF

selenium.keyPressNative("47"); // slash

selenium.keyPressNative("84"); // t

selenium.keyPressNative("79"); // o

selenium.keyPressNative("79"); // o

selenium.keyPressNative("76"); // l

selenium.keyPressNative("83"); // s

selenium.keyPressNative("47"); // slash

selenium.keyDownNative("16"); //SHIFT ON

selenium.keyPressNative("70"); // f shift makes it F

selenium.keyUpNative("16"); // SHIFT OFF

selenium.keyPressNative("73"); // i

selenium.keyPressNative("76"); // l

selenium.keyPressNative("69"); // e

selenium.keyPressNative("46"); // .

selenium.keyPressNative("84"); // t

selenium.keyPressNative("88"); // x

selenium.keyPressNative("84"); // t

selenium.keyPressNative("10"); // Enter

selenium.keyReleaseNative("10"); // Enter

I ve ended the sequqnce with an Enter character. Sometimes this doesn t work so you may need to click the button (if you know the element locator for it).

问题回答

This is an old question but I recently solved the problem doing this

    //Start an auto it script that selects the file manually
    if(browser.contains("iexplore")){
        Runtime r= Runtime.getRuntime();
        Process p = null;
        try {
            p = r.exec("C:\uploadFile.exe  "Files" "ctl00$ContentPlaceHolder1$FilesView$ctl02$NewFile" "C:\GhostTagBug2.ttx"");

        }catch(Exception e){}
        p.waitFor();
    } else {
        //Tested on firefox
        //Get focus and type the path manually
        selenium.focus("xpath=//input[contains(@id,"_NewFile")]");
        selenium.type("xpath=//input[contains(@id,"_NewFile")]", "C:\GhostTagBug2.ttx");
    }

browser is just a variable containing what browser the Selenium script is running and the code is obviously in java.

For IE, uploadFile.exe is an auto it script that looks like this.


#include IE.au3
AutoItSetOption("WinTitleMatchMode","2") ; set the select mode to select using substring

;Normally run from command line
if($cmdLine[0] > 2) then 
    $titlex = $cmdLine[1] ;Title of the window
    $form = $cmdLine[2] ;Name of the file upload/save form object
    $file = $cmdLine[3] ;Path of the file to upload
Else
    ;Testing fields
    $titlex = "Files"
    $form = "ctl00$ContentPlaceHolder1$FilesView$ctl02$NewFile"
    $file = "C:\GhostTagBug2.ttx"
EndIf

WinWait($titlex) ; match the window with substring
$title = WinGetTitle($titlex) ; retrives whole window title
WinSetState($title, "", @SW_MAXIMIZE) ;Maximize the window incase button is hidden
WinActivate($title)
WinWaitActive($title)

$oIE = _IEAttach ("Files")
$oT = _IEGetObjByName ($oIE, $form)
;Move the mouse to the button on the form and click it
MouseMove (_IEPropertyGet ($oT, "screenx") + _IEPropertyGet ($oT, "width") - 10, _IEPropertyGet ($oT, "screeny") + _IEPropertyGet ($oT, "height") / 2)
MouseClick ("left")

;Wait for upload screen then input the file and close it
WinWait ("Choose File to Upload")
$hChoose = WinGetHandle ("Choose File to Upload")
ControlSetText ($hChoose, "", "Edit1", $file)
ControlClick ($hChoose, "", "Button2")

;Restore window state
WinSetState($title, "", @SW_RESTORE)

It essentially grabs the title of the window, maximizes it, inputs the file to be uploaded, clicks the select button and goes back to Selenium, I ve tested it in IE 8 fine, but I don t see why any IE that is supported by auto it s _IE library wouldn t be able to handle this.

I ve seen a lot of robot scripts and firefox hacks where you enable javascript to do extra things. Both of these require no modification of the browser.

I apologize for lack of comments, this code is still in progress.

"fileLocator" is not an url but a locator as specified at top in the javadoc of the Selenium class. It is the locator of the input used to select a file.

The "fieldLocator" is an url pointing to the file you want to set in the input field of the form, as specified in the doc you are quoting.

With Firefox in chrome mode (browserId=*chrome instead of *firefox), this works as expected. It is documented to be working only with this browserId)

For instance : attachFile("uploadField", Thread.currentThread().getContextClassLoader().getResource("files/sample.pdf").toString());

My solution to this is to use Selenium-2 in RC emulation mode. This allows you to keep your legacy Selenium-1 tests but switch to Selenium-2 api when needed to perform tasks like file uploads.

Selenium-2 is currently in Beta but seems to be relatively stable. But not everything that Selenium-1 can do is supported by Selenium-2 RC emulation mode so think twice before you go that way.

More on this here: http://seleniumhq.org/docs/09_webdriver.html#emulating-selenium-rc

Using Selenium / Rspec / Internet Explorer My solution was to create an AutoIt script on my windows machine

WinWaitActive("Choose File to Upload")
Send("c:	estsschool.jpg")
Send("{ENTER}")
run("selectfile2.exe")

Then run this as an administrator on the windows machine. Right-click on the exe file and run as admin.

Then rspec does a page.click "id of your browse button". When the Browse Window opens on the windows machine, AutoIt autofills the text box and it closes. Hopes this helps someone because this was driving me nuts.

You may try this script in AutoIt. Basically, it awaits for file chooser window. Then enters file path and send enter quick. At the end checks if there was any popup error message, if any reads it text and set exitcode to 1, if non set exit code to 0. The script also ensures that file chooser window is closed.

The script can be converted to executable (.exe) by Aut2Exe - it s important to mark console? checkbox, After that exe can and executed from java (Runtime.getRuntime().exec()).

There is also one thing important to run click on file upload button in separate thread.

new Thread() {
  public voi run() {
    browser.click([LOCALTOR]).
 }
}.start();

Otherwise selenium will hang awaiting for click command finish, which never happens because File Chooser windows was opened and not closed.

The script:

$title="Choose File to Upload"
If($cmdLine[0] == 1 OR $cmdLine[0] == 2) Then
    $file=$cmdLine[1]
    If ($cmdLine[0] == 2) Then
        $title=$cmdLine[0]
    EndIf
Else
    ConsoleWriteError("Wrong number of argument. Use 2 argument: [FILE PATH] [FILE UPLOAD WINDOW TITLE]. Second argument is optional")
    Exit(-1)    
EndIf


If WinWaitActive($title,"",5)==0 Then ; wait 5 sec. 
    ConsoleWriteError($title & " window wasn t opened")
    Exit (2)
EndIf

Send($file)
Send("{ENTER}")

$status=WinWaitActive($title, "", 1)
$success = ($status = 0)

If Not $success Then
    $text =  ControlGetText($title,"","[CLASS:Static; INSTANCE:2]")
    WinClose($title)    
    WinClose($title)    
    ConsoleWriteError($text)
EndIf

Exit Not $success

Its much easier using $sel->type and $sel->focus. Below is a good article.

http://bitsilearn.blogspot.com/

I just succesfully uploaded files using Selenium set to use *firefox as the browser. I guess they haven t updated the documentation yet.

I am using the Ruby client so it was something like this to get it to work

$browser.click "css=input.file" # This is the  Choose File  button
$browser.type "css=input.file", "/absolute/path/to/file.file"




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签