Working around file upload dialog issues with Selenium 2

One of the most common issues found when using Selenium 2 (and other browser automation tools), is dealing with dialogs, such as alerts and browser upload/downloads. I recently encountered this problem again with a file upload dialog, and I wanted to share my solution.

I use Selenium2/WebDriver to control navigation up to the point where the upload dialog is opened, although any browser automation tool would do the trick. I then execute an AutoIt script to complete the interaction with the dialog. I then run a seperate batch file to kill AutoIt after the dialog has been handled. By looping through these steps, I can process a List of files to be uploaded.


private void uploadAllFilesInBrowser(List<String> filesToBeUploaded) {
try{
	openBrowser();
	goToUploadPage();
	uploadAllFilesInUploadDialog(filesToBeUploaded);
}
finally{
	closeBrowser();
    }
}

private void uploadAllFilesInUploadDialog(List<String> filesToBeUploaded) {
	for(String file : filesToBeUploaded){
		openUploadDialogAndUploadFile(file);
	}
}

private void openUploadDialogAndUploadFile(String filename) {
	openUploadDialog();
        runAutoItFileUpload(filename);	
	killAutoIt();
}

private void runAutoItFileUpload(String filename) {
	Runtime.getRuntime().exec(pathToAutoit + "\\AutoUploadAsset.exe \"" + filename);
}

private void killAutoIt() {
	Runtime.getRuntime().exec("cmd /C start /min " + pathToAutoIt + "\\KillAutoIt.bat");
}

Below is the code for the AutoUploadAsset.au3 file. The AutoIt file, when opened, will enter an infinite loop, waiting for the “File Upload” window to appear. When it does appear, it will enter the filename into the upload field, wait a second, and click the upload button.


While 1
   
	If WinExists("File Upload") then
		ControlSetText('File Upload',"","Edit1", $CmdLine[1])
		
		sleep(1000)
		
		ControlClick('File Upload',"","Button1")
	Endif

   sleep(1000)
Wend

In order for the AutoIt script to be executed in Java with the Runtime.getRuntime().exec() method, it needs to be compiled as an executable. On Windows, right-click on the AU3 file and choose “Compile Script”. An AutoUploadAsset.exe will be created.

Since the AutoIt script is in an infinite loop, we need one final step to kill it, otherwise the same file will be uploaded over and over when the file upload dialog appears. The code below is the KillAutoIt.bat called in the killAutoIt() method.


@echo off
SET root=%~dp0

taskkill /f /fi "IMAGENAME eq AutoUploadAsset.exe"

@echo Killed AutoIt
@echo.
exit

This solution was mostly taken from a similar post at testingexcellence (http://www.testingexcellence.com/how-to-upload-files-using-selenium-and-autoit)

This entry was posted in Test Automation and tagged , , , , , . Bookmark the permalink.

Leave a comment