Content

File uploads

From the browsers point of view the file upload is supported using a special input control. You can find some basics here.
To trigger the file upload from HtmlUnit you have to

  • get the page
  • find the file input element
  • assign the path to the file you like to upload to the file input
  • submit the form (by pressing the button like the user does)

Upload a file using the path to a local file

HtmlPage firstPage = client.getPage(URL_FIRST);
HtmlForm f = firstPage.getForms().get(0);
HtmlFileInput fileInput = f.getInputByName("myInput");

String path = getClass().getClassLoader().getResource("testfiles/" + "tiny-png.img").toExternalForm();
fileInput.setValueAttribute(path);
firstPage.getHtmlElementById("mySubmit").click();

Upload file content from memory

HtmlPage firstPage = client.getPage(URL_FIRST);
HtmlForm f = firstPage.getForms().get(0);
HtmlFileInput fileInput = f.getInputByName("myInput");

fileInput.setValueAttribute("dummy.txt");
fileInput.setContentType("text/csv");
fileInput.setData("My file data".getBytes());
firstPage.getHtmlElementById("mySubmit").click();

Upload multiple files (if the 'multiple' attribute is set for the file input control)

String filename1 = "HtmlFileInputTest_one.txt";
String path1 = getClass().getResource(filename1).toExternalForm();
File file1 = new File(new URI(path1));

String filename2 = "HtmlFileInputTest_two.txt";
String path2 = getClass().getResource(filename2).toExternalForm();
File file2 = new File(new URI(path2));

HtmlPage firstPage = client.getPage(URL_FIRST);
HtmlForm form = firstPage.getForms().get(0);
HtmlFileInput fileInput = form.getInputByName("myInput");

fileInput.setFiles(file1, file2);

firstPage.getHtmlElementById("mySubmit").click();