Approaches for uploading file in Selenium tests

How upload file works

The process of uploading an image can be divided into two steps:

  • Select a File (Browse): To enable the user to pick a file, the first step is to add the input tag to App component. This input tag have the type attribute set as “file”. an event handler will listen to any changes made to the file. This event handler will be triggered whenever the user selects a new file and will update the state.
  • Send a request to the server: After storing the selected file (in the state), it will send the request uploading file to the server.

Problem when click browse file : When we click on “Browse” button on a web page, an native windows popup will be displayed to enable user to select a specific file. And when that popup opens, Selenium WebDriver cannot handle it, it is outside of Selenium world.

There is several options to handle a file upload in Selenium tests as mention below. However, I would prefer to use the built-in features provided by Selenium to upload a file using method SendKeys . There is no need to simulate the clicking of the “Browse” button. Other options also have a limitation to run on multiple platforms.

I. Upload Files Using webElement.Sendkeys() 

Using Selenium element.sendkeys() method, it will directly add the file path to input tag which have an attribute as  type=’file’.

WebElement addFile = driver.findElement(By.xpath(".//input[@type='file']"));
addFile.sendKeys("D:\\myfolder\\c1.jpeg");

II. Upload Files Using Robot Class

The Robot class is an AWT class package in Java. This is also a very good option to choose for the Upload file in selenium. This will help to automate a Windows-based alert or pop up, print pop up or native Windows screen. This is independent of the Operating System. 

refer more detail in this link

III. Upload File Using AutoIT 

AutoIT is an external automation tool and not provided by the Selenium community. Initially, AutoIT was used to automate native Windows related pop-ups, however, a drawback of using AutoIT is that it creates .exe file and runs only on Windows. It is not advisable to use AutoIT for file uploads.

refer more detail in this link

Demo Page: https://blueimp.github.io/jQuery-File-Upload/ http://demo.guru99.com/test/upload/

Leave a comment