File uploads
From the browser's perspective, file uploading is supported using a specialized input control. You can review basic web concepts on the MDN Web Docs.
To trigger a file upload programmatically in HtmlUnit:
- Fetch the target page containing the upload form.
- Locate the file input element (
HtmlFileInput). - Assign the local file path or raw data payload to the file input.
- Submit the form (e.g., by clicking the submit button).
Upload a file using the path to a local file
HtmlPage firstPage = client.getPage(URL_FIRST);
HtmlForm form = firstPage.getForms().get(0);
HtmlFileInput fileInput = form.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 form = firstPage.getForms().get(0);
HtmlFileInput fileInput = form.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)
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();

