I am trying to upload a file to a website using the HtmlUnit HtmlFileInput class. I have the data in a byte[] array and would like to send it up without writing it to a file first.
I'm trying:
HtmlFileInput fileInput = form.getInputByName("file");
fileInput.setData(data);
HtmlElement button = form.getInputByName("validate");
HtmlPage responsePage = button.click();
This is not working. But, when I try
HtmlFileInput fileInput = form.getInputByName("file");
fileInput.setValueAttribute("file.txt");
HtmlElement button = form.getInputByName("validate");
HtmlPage responsePage = button.click();
Everything works fine. The docs seem to indicate that setData() does exactly what I want to do, but it doesn't seem like any of the HtmlUnit code even uses the data_ variable that is set when setData() is called. The code uses the files_ field which is set when setValueAttribute() is called.
I noticed several old bugs that were opened that talked about similar problems and it says that they were all fixed.
Am I trying to use setData() in a way that it shouldn't be used?
Thanks.
In short - data_ is used by getSubmitNameValuePairs() and there are also unit tests for that (e.g. com.gargoylesoftware.htmlunit.html.HtmlFileInput2Test.setValueAttributeAndSetDataDummyFile()).
The trick here is the missing rest of the file - you have to simulate a bit more if you like to get your stuff uploaded. Please set the Value (to submit a dummy file name) and the content type also to help the server to understand your data.
HtmlFileInput fileInput = form.getInputByName("file");
fileInput.setValueAttribute("dummy.txt");
fileInput.setContentType("text/csv");
fileInput.setData("My file data".getBytes());
I think i have to improve the documentation for this a bit.
If you like we can discuss this or if you like to see a quick fix - simply open an issue on github.
Related
How to upload files from local via window prompt using selenium webdriver?
I want to perform the following actions:
click on 'Browse' option on the window
from the window prompt go to the particular location in the local where the file is kept
select the file and click on 'Open' to upload the file.
Have you tried using input() on proper file input control?
WebElement fileInput = driver.findElement(By.id("some id"));
fileInput.sendKeys("C:/path/to/file.extension");
I have used below three different ways to upload a file in selenium webdriver.
First simple case of just finding the element and typing the absolute path of the document into it. But we need to make sure the HTML field is of input type. Ex:<input type="file" name="uploadsubmit">
Here is the simple code:
WebElement element = driver.findElement(By.name("uploadsubmit"));
element.sendKeys("D:/file.txt");
driver.findElement(By.name("uploadSubmit"));
String validateText = driver.findElement(By.id("message")).getText();
Assert.assertEquals("File uploaded successfully", validateText);
Second case is uploading using Robot class which is used to (generate native system input events) take the control of mouse and keyboard.
The the other option is to use 'AutoIt' (open source tool).
You can find the above three examples : - File Uploads with Selenium Webdriver
Selenium Webdriver doesn't really support this. Interacting with non-browser windows (such as native file upload dialogs and basic auth dialogs) has been a topic of much discussion on the WebDriver discussion board, but there has been little to no progress on the subject.
I have, in the past, been able to work around this by capturing the underlying request with a tool such as Fiddler2, and then just sending the request with the specified file attached as a byte blob.
If you need cookies from an authenticated session, WebDriver.magage().getCookies() should help you in that aspect.
edit: I have code for this somewhere that worked, I'll see if I can get ahold of something that you can use.
public RosterPage UploadRosterFile(String filePath){
Face().Log("Importing Roster...");
LoginRequest login = new LoginRequest();
login.username = Prefs.EmailLogin;
login.password = Prefs.PasswordLogin;
login.rememberMe = false;
login.forward = "";
login.schoolId = "";
//Set up request data
String url = "http://www.foo.bar.com" + "/ManageRoster/UploadRoster";
String javaScript = "return $('#seasons li.selected') .attr('data-season-id');";
String seasonId = (String)((IJavaScriptExecutor)Driver().GetBaseDriver()).ExecuteScript(javaScript);
javaScript = "return Foo.Bar.data.selectedTeamId;";
String teamId = (String)((IJavaScriptExecutor)Driver().GetBaseDriver()).ExecuteScript(javaScript);
//Send Request and parse the response into the new Driver URL
MultipartForm form = new MultipartForm(url);
form.SetField("teamId", teamId);
form.SetField("seasonId", seasonId);
form.SendFile(filePath,LoginRequest.sendLoginRequest(login));
String response = form.ResponseText.ToString();
String newURL = StaticBaseTestObjs.RemoveStringSubString("http://www.foo.bar.com" + response.Split('"')[1].Split('"')[0],"amp;");
Face().Log("Navigating to URL: "+ newURL);
Driver().GoTo(new Uri(newURL));
return this;
}
Where MultiPartForm is:
MultiPartForm
And LoginRequest/Response:
LoginRequest
LoginResponse
The code above is in C#, but there are equivalent base classes in Java that will do what you need them to do to mimic this functionality.
The most important part of all of that code is the MultiPartForm.SendFile method, which is where the magic happens.
I want to use HTML Unit for JAVA.
In all examples there will be read the HTML Code from a specific website.
But I want to read the HTML source from another String.
Like this:
String myString = "<html> myString and Content </html>";
HtmlPage page = myString; // doesn´t work, how can I do something like this?
I see only examples like this:
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
Can I also read only a Table?
Like this:
String myTable = "<table><td></td></table>";
HtmlTable table = myTable; // doesn´t work, how can I do something like this?
My question is now, how can I convert this correct?
Can anybody help me, please.
HtmlUnit isn't really designed for this use case, so it will always be a bit of a hassle to make it work. If you're not tied to HtmlUnit specifically, you might be better off using something like jsoup, which has better built-in support for parsing HTML from strings.
That said, if you are tied to HtmlUnit, it's possible to make this work. For inspiration, you could look at how HtmlUnit sets up HtmlPage objects in its own test suite.
As you can see there, although there's no way to construct an HtmlPage directly from a String, you can make a MockWebConnection that'll give a canned response without involving the network. So your code could look something like this:
String html = "<html>Your html here</html>";
WebClient client = new WebClient();
MockWebConnection connection = new MockWebConnection();
connection.setDefaultResponse(html);
client.setWebConnection(connection);
HtmlPage page = client.getPage(someUrl);
(Apologies for any errors in the above -- I'm no longer on a Java project, so I don't have a convenient way to test this right now. That said, I did spend some time on a large Java project that used roughly this technique for a lot of tests. It worked reasonably well, but it tended to be a bit fragile when we upgraded HtmlUnit. Overall, we were happier when we moved to Jsoup.)
Here is another way of doing it, similar to Collum's but a little different.
WebClient webClient = new WebClient();
URL url = new URL("http://example.com");
WebRequest requestSettings = new WebRequest(url, HttpMethod.GET);
StringWebResponse response = new StringWebResponse("<html> myString and Content </html>", url);
HtmlPage page = HTMLParser.parseHtml(response, webClient.getCurrentWindow());
As for getting the table, it is possible. You can load it with the method above and extract it with the code below.
HtmlTable table = page.getHtmlElementById("table1");
you can iterate over and cells with the code below
for (final HtmlTableRow row : table.getRows()) {
System.out.println("Found row");
for (final HtmlTableCell cell : row.getCells()) {
System.out.println(" Found cell: " + cell.asText());
}
}
and you can access specific cells with the example below
System.out.println("Cell (1,2)=" + table.getCellAt(1,2));
Please comment if you get stuck and I may be able to help
If I have a HTML String object, using Selenium in Java, how can I get the browser to open that String as a HTML page? I have seen this done before but I don't remember the format that the URL needs to be.
For this example, let's say the string is :
<h2>This is a <i>test</i></h2>
I looked through this page and couldn't find the answer but I might be overlooking it. For example I tried this URL and it didn't work for me:
data:<h2>This is a <i>test</i></h2>
Here is a link for documentation http://en.wikipedia.org/wiki/Data_URI_scheme. You need to specify MIME-type of data. Try data:text/html,<h2>This is a <i>test</i></h2>
I want to be able to display on the browser a file with wicket. I have a form witch takes the id and storage area of the document, then by pressing the submit button, I would like to display the file on the browser if it's possible else download it.I get the file as a byte [], it's compulsory, I cannot have it another way. I searched a lot for some answers but the fact that I'am using wicket 6.8.0 is handicapand because every solution that I find uses some obsolete methods (for the 6.8.0 version).
My question is: Is there any one who can help me do this without changing the wicket version (I cannot change it). The solution doesn't have to be in wicket.
Sorry if my English is incorrect
Thank you in advance
I found it. For persons who want to do this with wicket 6.8.0, it's the solution. It's quite simple though. Here's the code:
WebResponse fileResponse = (WebResponse) getRequestCycle().getResponse();
fileResponse.setContentType(mimeType);
fileResponse.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
fileResponse.write(myByteFile);
getRequestCycle().setResponse(fileResponse);
I get the file type by using the Tika API.
i want to use pdfjet for a Google app engine project.
i downloaded the Java jar from the pPdfjet home page.
i followed an example given in a stack-overflow example and the examples given in the home page.
all the examples uses an empty constructor: PDF pdf=new PDF();. However when i try to use it,
it says that the constructor PDF() is undefined, further more all the method shown do not work:
pdf.wrap(): is undefined
pdf.save("Example_03.pdf"): is undefined
It looks like the examples on their web page are out of date. Look at the examples in the zip download instead. This simple example works for me:
OutputStream out = new FileOutputStream("test.pdf");
PDF pdf = new PDF(out);
Page page = new Page(pdf, Letter.PORTRAIT);
pdf.flush();
out.close();
Ok this is easy. Actually instead of taking from req.getOutputStream() directly create and instance of BytArrayOutputStream and use that.
For sending it just use out.toArray() as add it to the attacement part.