Submit API File Example
Here, we’re going to look at how to submit a form containing a file upload field through the API. The form that we’ll be using is very similar to the basic example form, with the exception that there is a file upload field. If you’re looking for the basics of how the API works, please read the basic example form documentation.
Download the Files
Oftentimes, the easiest way to learn something is by taking a look at the actual working code, installing it on your servers, and playing around. So here are the exact files needed in order to get this basic api example working.
Building the Form
Just like before, you can copy and paste the form code that is found on the actual Wufoo form. Here is the live Wufoo form that this example is based off of.
File Upload Field
If you’re not an HTML expert, a file upload field is pretty straightforward to add. It’s similar to a text field except that the type is “file”.
<input id="Field2"
name="Field2"
class="field text"
type="file" />
Building the POST string
Much like we do with all of the other fields, the file that was uploaded will be built in the POST string that is sent to Wufoo. The only difference is that a file upload field will require two variables. One variable is for the file’s name, and the other one is for the file’s contents.
function setPostParams(){
$wufoo_query_vals = array(
'w_api_key' => '0000-0000-0000-0000',
'w_form' => 'contact-me-form-w-file-upload',
'0' => $_POST['Field0'],
'1' => $_POST['Field1'],
'2' => getFile('Field2'),
'File-2' => $_FILES['Field2']['name']
);
return $wufoo_query_vals;
}
the getFile Function
If you look in the code above, you’ll see a function called getFile(). This function is responsible for opening up the file, and returning the file’s contents as a string.
function getFile($fieldName){
//name of the file
$file = $_FILES[$fieldName]['name'];
//location where file is coming from
$myFile = $_FILES[$fieldName]['tmp_name'];
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
//escape characters with addslashes()
$theData = addslashes($theData);
fclose($fh);
return $theData;
}