how to do image upload from a folder in selenium webdriver java - java

I am automating mobile website using selenium.
In my test case I need to upload image. There is one camera image with id addimage on click of which file upload popup is shown. Check images of this flow
HTML code for this :
<div class="clearfix">
<ul id="imageList"> </ul>
<div id="uploadimginput">
<a id="addimage" class="sprite camera"> </a>
</div>
<input id="image" class="w0" type="file" name="image">
</div>
Multiple image upload :
From file upload popup i want to open a folder "testimages" and then select an image.
How can I do this in selenium java.

Don't click on the image itself so that the popup will not appear.
In your html code there should be an input element with type file. In your Selenium test you can find the input element and fill it with the path of the image you want to add. Then submit the form around the input element.
The Selenium framework will handle the rest for you. For me it works fine with all browsers.
I think its a cleaner solution than simulation a keyboard.

From what I can see, this is a Window dialog box and it is out of the context of browser, and hence can't be automated directly by Selenium. Hence, you will have to use Robot/Sikuli/Autoit for that.
Below code is the way by using "Robot class" . For using this, do import all the classes from "java.awt package" namely java.awt.Robot, java.awt.event.KeyEvent, java.awt.Toolkit, java.awt.datatransfer.StringSelection, java.awt.AWTException alongwith the rest necessary imports:
Edited the Code for multiple file upload (Works in FF, IE and Chrome):
//Code for clicking on the image button that brings up the window dialog box
...
//Putting all the absolute paths of the pics to upload(here, 3 files)
String arr[] = {"\"D:\\Pic1.jpg\"", "\"D:\\Pic2.jpg\"", "\"D:\\Pic3.jpg\""};
//Copying the path of the file to the clipboard
StringSelection photo = new StringSelection(arr[0]+arr[1]+arr[2]); //Putting the path of the image to upload
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(photo, null);
//Pasting the contents of clipboard in the field "File name" of the Window Pop-up
Thread.sleep(5000); //Some sleep time to detect the window popup
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
//To Click on the "Open" button to upload files
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Related

Selenium Upload File On file selection doesn't enable submit button

I've tried
File file = new File("/Users/swapnil.kotwal/Desktop/AntVsGradle.jpg");
driver.findElement(By.xpath("//input[#class='libray_create-resource_choose-file_hidden-input']")).sendKeys(file.getAbsolutePath());
And My HTML is something like below
<div class="libray_create-resource_choose-file">
<button class="btn is-hollow_blue libray_create-resource_choose-file_button undefined">Choose File</button>
<input type="file" class="libray_create-resource_choose-file_hidden-input">
</div>
<div class="library_create-modal_footer">
<button class="btn is-text_only btn-cancel undefined">Cancel</button>
<button class="btn is-filled_blue undefined" disabled="">Add</button>
</div>
I found that file input which is hidden got the file path set properly.
The problem is there Choose File button element is different from file input element //input[#class='libray_create-resource_choose-file_hidden-input']"
There seems to some JS event which make final Add button enable on click of Choose File button.
So, I imported file into file HTML element but how can I enable Add button?
I tried to make that button enabled
WebElement yourButton= driver.findElement(By.className("is-filled_blue"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].removeAttribute('disabled','disabled')",yourButton);
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(yourButton));
It makes that button visible but still not allow to actually click on it.
First let me say that -- I don't program in Java, -- but I do a lot of selenium coding in Python.
When I was looking at this question from purely a selenium view point I noted that you aren't selecting the choose file button prior to sending your input. I would assume that you have to select this button to enable the element - btn is-filled_blue undefined
Here is some pseudocode that might help trigger that button to switch from disabled to enabled.
File file = new File("/Users/swapnil.kotwal/Desktop/AntVsGradle.jpg");
WebElement select_button = driver.findElement(By.xpath("//*[#class='btn is-hollow_blue libray_create-resource_choose-file_button undefined']"));
select_button.click();
WebElement upload_file = driver.findElement(By.xpath("//input[#class='libray_create-resource_choose-file_hidden-input']"));
upload_file.sendKeys(file.getAbsolutePath());
/* You might need to send an Enter, Return or Tab before the
add_file_button changes. This process requires testing on the website.
upload_file.sendKeys(Keys.ENTER);
upload_file.sendKeys(Keys.RETURN);
upload_file.sendKeys(Keys.TAB);
*/
boolean add_file_button_presence = driver.findElement(By.className("is-filled_blue")).isDisplayed();
boolean add_file_button_enabled = driver.findElement(By.className("is-filled_blue")).isEnabled();
if (add_file_button_presence==true && add_file_button_enabled==true)
{
WebElement add_file_button = driver.findElement(By.className("is-filled_blue"));
add_file_button.click();
}
Since I don't normally program in Java the structure and syntax of my pseudocode could be incorrect. If it is please let me know and I will either delete this answer or correct the issues with some research.
That undefined class looks suspect - try removing it by adding another js call:
js.executeScript("arguments[0].style.removeProperty('undefined')",yourButton);
My suggestion would be always limit the usage of JavaScript(JavascriptExecutor) code to an extent it simulates the end user action and not manipulates the application behavior
like enabling a button which is disabled functionally etc.
Our purpose is to simulate the application steps in the same way how an end user would use it.
I would suggest to use any third part tool like AutoIt/Sikuli to handle this case since sending file path doesn't enable the 'Add' button automatically as expected
1)Click on the 'Choose File' button using Selenium which opens the upload window, which is not a web component.
2)Since Upload window is not a web component Selenium doesn't support it.
3)Use any third party tools like AutoIt/Sikuli to handle the Windows upload popup by setting the filepath and submit.
4)As we are uploading the file in the UI in the same way how an end user would do, 'Add' button will be enabled automatically.
AutoIt
Try to use JavascriptExecutor to click it too, before you remove disabled attribute.
WebElement element = driver.findElement(By.xpath("xpath"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
If you use JavascriptExecutor you dont need to make it visible
I managed to upload file by using below hack... I never click on Choose File link/button which was launching Upload File Windows pop-up and by any mean that windows pop-up was not going away.
Tried below options.
1.
select_button.click();
select_button.submit();
action.sendKeys(Keys.ESCAPE).perform();
select_button.sendKeys(Keys.ESCAPE);
robot = new Robot();
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
none of this hiding that pop-up on Mac OS
So, I found a Jugad(#hack in English) I never click on Choose File button which were launching that Upload File Window
public void uploadFile() {
WebElement element = driver.findElement(By.className("libray_create-resource_choose-file_hidden-input"));
element.sendKeys("/Users/swapnil.kotwal/projectName/automation.pdf");
WebElement addButton = driver.findElement(By.className("is-filled_blue"));
// click was important, thanks to this answer in this thread https://stackoverflow.com/a/67095019/1665592
driver.executeScript("arguments[0].click();", addButton);
driver.executeScript("arguments[0].removeAttribute('disabled','disabled'); arguments[0].style = \"\"; arguments[0].style.display = \"block\"; " +
"arguments[0].style.visibility = \"visible\";", addButton);
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(addButton));
addButton.click();
}

How to upload a file without using autoit and with only using selenium and java?

Here is the button inspect element for which file upload is not working
<button class="btn btn-success text-capitalize" id="ac-btn-imprt" type="button">Browse File</button>
So when I try to do sendkeys, it doesn't work because for send keys it has to be the input tag in my case it is as type=button.
Thanks in advance.
Note
I am using selenium with java to automate my application.
I have used robot class which works intermittently and i couldn't able to debug the robot class implementation as I haven't worked on it.
You can use ROBOT API jars to upload the file.
Simply trigger the browse button and when you need to give the location of your file to upload use Robot API to send the location and then again using Robot API press enter.
try {
//Setting clipboard with file location
setClipboardData(fileLocation);
//native key strokes for CTRL, V and ENTER keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception exp) {
exp.printStackTrace();
}
Add LocalFileDetector to driver if you using RemoteWebDriver:
driver.setFileDetector(new LocalFileDetector());
Find hidden <input type="file"> in HTML and sendKeys absolute path to file.
Details you can find:
How to upload file using Selenium WebDriver in Java
https://sqa.stackexchange.com/questions/12851/how-can-i-work-with-file-uploads-during-a-webdriver-test

Upload photo button not working in Selenium Webdriver

Upload photo button not working in Selenium Webdriver
What I have already tired
driver.findElement(uploadPhotoBtn).sendKeys("E:\\photo.png");
Also tried the Robot function
driver.findElement(uploadPhotoBtn).click();
StringSelection ss = new StringSelection(logoPath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Same Robot function working for another upload button, but while trying to use here, the .click not working that is why unable to use the Robot function.
HTML page source:
> <div ng-show="!status.uploading" ng-class="{ '!isMobile':
> 'mewe-type-1' }" class="uploader-able !isMobile"><!-- ngIf: isMobile
> --><!-- ngIf: !isMobile --><button ng-if="!isMobile" class="btn-action radius ng-scope">Upload Photo</button><!-- end ngIf: !isMobile
> --><input capture="camera" accept="image/*" name="image" type="file" fileread="fileread" file="file" class="ng-isolate-scope"></div>
Console log:
org.openqa.selenium.WebDriverException: unknown error: Element ... is
not clickable at point (314, 477). Other element would receive the
click:
(Session info: chrome=66.0.3359.181) (Driver info:
chromedriver=2.35.528161
This is example of how to add file to upload button, don't quite sure what is path of button, but You have to find element with <input type="file"> element and interact with it:
WebElement uploadPhotoBtn = driver.find(By...); //type="file"
File file = new File(path);
uploadPhotoBtn.sendKeys(file.getAbsolutePath());
...and this is how to get source, if You have some kind of preview
elementPreview.findElement(By.tagName("img")).getAttribute("src");
Hope this helps,
A couple of things:
1) The "Element is not clickable" error means that the upload button is covered somehow. That could be it is disabled, behind some cover, or my favorite, the whole page clear div. Make sure that the button you're trying to click is truly available for clicking...
2) For the .sendKeys() to work, you need to point to the <input type="file"> element. Based on the variable name, you're trying to point to the <button> webelement instead.
As according the Error which you are getting, try to solve it by any of below, replacing click event:
Actions act = new Actions(wd);
act.moveToElement("Your Webelement").click().perform();
OR you can operate with JavaScript functionality,
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", "Your Webelement");
You need to 'type' your file into the input element. Your above send keys command isn't quite right.
Code you can try:
driver.findElement(By.xpath("//input[#name="image"]")).sendKeys("Image Path Here") ;
My answer was criticized at one SO post by #JimEvans, who is a core contributor to the Selenium web automation framework. I learned something from him. This is what he had to say about upload button with <input type="file">.
If you are trying to upload a file, and the page in question uses the standard upload mechanisms provided by HTML, you can do this directly with Selenium itself. The standard HTML mechanism is with an <input type="file"> element. Once you’ve found that file upload element on the page, you can use element.sendKeys("full/path/and/file/name/here");. This is documented in Step 10 of the algorithm for the Element Send Keys command of the W3C WebDriver Specification and is used in several file upload tests in the Selenium project’s test code example.
WebElement upload = d.findElement(By.xpath("//*[#name='filename']"));
Thread.sleep(2000);
Actions action = new Actions(d);
action.moveToElement(upload);
action.click().build().perform();
Thread.sleep(2000);

Selenium: Saving pdf which is opened in new browser without url

Can someone guide me how I can achieve the following:
I am using selenium web driver java.
Whenever I click the preview button on the webpage, the pdf is opened in a new browser and I need to save that pdf with the name given dynamically.
So far I am able to click the preview button and a new browser is opened with the pdf. Here the browser doesn't have url.
After the pdf is open I am sending keys control+s.
Then save dialog window appears. I am stuck here about how to save pdf to the local drive.
The main browser is IE but i am trying in Firefox first
You can try this code :-I think this is what you are looking for. let me know If this what you are expecting.
System.setProperty("webdriver.gecko.driver", "D:/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(2000);
java.awt.Robot robot = new java.awt.Robot();
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_TAB); // file replace move to yes button
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER); // hit enter
Just first execute the code, see if it is working, and is it what you want.
Last three lines of code are written for replace existing pdf file. So you just first comment those three lines, execute the code and from next time, include last three lines of code
You need to use Robot Class to handle events.
And let me know whether this is working at your end.
I think you should try to download the file immediately instead of trying to manage that browse window.
You can set the attribute download of the a element, and then click on the element. See code below:
WebElement pdf = driver.findElement(By.cssSelector("a"));
String script = "arguments[0].setAttribute('download');"
((JavascriptExecutor)driver).executeScript(script, pdf);
pdf.click();

JEditorPane doesn't want to show a button done in html (it shows in a browser)

I created a buttton in html and linked it to another html file, when i open the file with the button in a browser (tried IE and FFox) the button shows and works properly, however when i JEditorPane.setPage(the html file with the button) the only thing that shows is the name of the button with no actual clickable area or anything! Any ideas on how i can get the button to appear inside the pane?
Here's a pic of the button in the java frame(button is circled in red)
http://tinypic.com/r/fopswo/6
Here's a pic of the button in a browser(it's a button)
http://tinypic.com/r/2zjj71z/6
The code for the button
<font size = 12 face = "verdana" ><u> Creating An Account </u></font>
<span style="padding-left:360px"> </span>
<button onclick="window.location.href ='file:///F:/java 12/Isp/help file try/doc 2/test.html'">Back</button>
Thanks in Advance
Swing's HTML support is patchy - I think you have fallen in one of its holes. More info here:
Which HTML tags are supported in Swing components?

Categories