When you are working in a testing company on the automation part then upload file scenario is the most common problem. There are 03 ways to automate the same.
- Using selenium
- Using AutoIT
- Using Robot class
Using Selenium: We can simply upload it using selenium if the HTML contains attribute input[@type='file']. if this thing is not present in the HTML part of the application then it won't be possible using selenium then we need to look into another alternative. If it is present then we can use below syntax for the same.
WebElement upload_file = driver.findElement(By.xpath("//input[@id='file_upload']"));
upload_file.sendKeys("C:/Users/abc/Desktop/upload.jpg");
Using AutoIT:
Open the AutoIT editor.
We need to write a simple code in AutoIT editor, required for file upload operation (the name of the file to be uploaded, will be mentioned in the code).
Now close the editor and right click on it, you will see compile script option.
Choose compile script (x64) option for 64 bit machine and go with compile script (x86) for a 32-bit machine.
As soon as the above step is completed, a .exe file is created and this file will be mentioned in our selenium eclipse code.
After compilation‘fileupload.exe’ file gets created.
Now we can make use of this file in the Selenium web driver script.
WebElement browser = d.findElement(By.xpath("//input[@id='pimCsvImport_csvFile']")); //Browse button
browser.click();
Runtime.getRuntime().exec("C:\\Users\\Chait\\Desktop\\autoit\\fileupload.exe");
Thread.sleep(3000);
WebElement upload = d.findElement(By.id("btnSave")); //Uploadbutton
upload.click();
System.out.println("File Uploaded Successfully"); // Confirmation message
When the program executes this line, it goes through the fileupload.exe file where the AutoIT code is executed as shown below:
ControlFocus("File Upload","","Edit1")
ControlSetText("File Upload","","Edit1","C:\Users\Chait\Desktop\autoit\data_file.csv")
ControlClick("File Upload","","Button1")
Robot Class
Its already covered above using the same we can upload.