This is a Browser Action API.
_setFile is used to set a file in the file input field.
Form elements of type “file” cannot be populated using javascript on the browser.
So Sahi has a workaround for handling file uploads.
Sahi intercepts the request in the proxy, reads the file off the file system and inserts it into the multipart request.
The file has to be present on that path on the machine running the proxy.
_setFile(element, filePath [, actionURL])
The parameters are:
_setFile(_file("id"), "C:\\abc\\efg.jpg");
_setFile(_file("id"), "C:\\abc\\efg.jpg", "formSubmit.jsp");
Note that _setFile works in a round about way. It is not handled at the browser level. It is handled at the proxy. So you will not see the file input box being populated with your desired filename. But when the form is submitted, the proxy will add the correct file to the request before it sends it to your web server. But if there are javascript checks before form submit to see if the filename is non-empty, then the script will not work as desired.
If there are javascript validations on the file field, you can try this hack. Before submitting the file, change the field’s type to “text”, and then set its value. Eg.
// set the file
_setFile(_file("file"), "scripts/demo/uploadme.txt");
// Change the "type" attribute of file field
if (_isIE()){
_call(_file("file").outerHTML = _file("file").outerHTML.replace(/type=file/, "type=text"));
}else{
_call(_file("file").type = "text");
}
// Set the value into the textbox
_setValue(_textbox("file"), "scripts/demo/uploadme.txt");
Troubleshooting
1) Look to see if there are any exceptions on the Sahi console (the command prompt). If it shows any FileNotFoundException, correct the path of your file.
2) Check if the URL to which the form is being submitted is correct. Sometimes the URL is changed when the form is submitted, and Sahi needs to be told about it using the 3rd parameter in _setFile
Complete examples on _setFile are available in sahi/userdata/scripts/demo/fileUpload.sah
It can be run with start URL http://sahi.co.in/demo/