# How to click a button to upload local file with WebExecute?

A webpage has a "browse" button to open the filesystem to select a file and upload it, in html it looks like this:

<input type="file" class="custom-file-input" id="img1" name="image">


If I have the path of the file, what is the WebExecute command I need to automate this?

This can not be done with WebExecute because opening files from the local file system is always handled with the operating system's file dialog. It would be a big security hole if a browser could open any file from your computer without your consent. And WebExecute only operates directly on a web browser (through a proxy binary), so it can not do that.

There is a way to get around this by using the RobotTools package (include in recent product layouts, but I can get you a copy if you need it).

First let's make a simple web page with your input field:

html = "<!doctype html>
<html>
<title>test</title>
<body>
<h1>test</h1>
<input type='file' class='custom-file-input' id='img1' name='image'>
</body>
</html";

CloudExport[html, "HTML", "test.html", Permissions -> "Public"]


Then start a session and open the page:

session = StartWebSession[]

WebExecute[session, "OpenWebPage" ->
"https://www.wolframcloud.com/objects/user-7053ce31-817f-4643-aec1-eda27051bba6/test.html"]


Then you run the RobotTools code (replace the file name with something from your own machine):

Needs["RobotTools"];

e = WebExecute[session, "LocateElements" -> {"Id" -> "img1"}];
WebExecute[session, "ClickElement" -> First[e]];
Pause[1];
KeyType["\[AltKey]\[LeftModified]\[TabKey]\[RightModified]"];
Pause[1];
KeyType["C:\\Users\\arnoudb.WRI\\Girl_with_a_Pearl_Earring.jpg"];
Pause[1];
KeyType["\[EnterKey]"];


To work with this code make sure that you only have two applications open: the Mathematica which runs the code and the Chrome web browser (or at least they should be the two 'top most applications' when you toggle applications with Alt-Tab).

The first two lines will open the system file dialog. The pauses make sure the application has time to respond to the robot commands (they can be made shorter). The first KeyType will switch applications (from Mathematica to Chrome). The second KeyType will type a verbatim file name in the system file dialog, and the final KeyType` will submit and close the system file dialog.

At this point the file name you typed should show up on this web page: