Software Development and QA Tips

Dev and QA Tips How to Upload an Image in Selenium WebDriver With JavaScript?

How to Upload an Image in Selenium WebDriver With JavaScript?

How to Upload an Image in Selenium WebDriver With JavaScript?

When you are working on the automation part in a testing company, then uploading a file scenario is the most common problem encountered by engineers. There are 2 ways to automate the same.

  1. Using Selenium
  2. Using AutoIT
  3. Using Robot class
 

Using Selenium:

We can simply upload the file using Selenium if the HTML contains attribute input[@type='file']. If this is not present in the HTML part of the application, then it will not be possible to upload using Selenium and we would need to look into an alternative. If 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:

Once you open the AutoIT editor, you 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, an .exe file is created and this file will be mentioned in our Selenium Eclipse code. After compilation, ‘fileupload.exe’ file gets created. Now, you can make use of this file in the Selenium WebDriver 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")

If you have any other questions or concerns about the Selenium web driver or are in general need of QA resources, contact QASource's testing experts.

Contact Us

Disclaimer

This publication is for informational purposes only and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.