I created a custom form with a file upload field:
$form['csvfile'] = array(
'#title' => 'CSV File',
'#type' => 'file',
);
When I submit the form, I can see the correct information in the $_FILES array:
However, when I try to use the code in the examples module to get the contents of that file and write it to an unmanaged file, the file is empty.
So, the resulting file is 0 bytes long.
How do I access the uploaded file in a drupal-y way? I know I can just use the basic PHP functions to access the file, but I'm trying to learn how to do it the way drupal intends.
My submit handler code is almost entirely lifted from the examples module.
function herdapi_form_bulkupload($form, &$form_state) {
$form = array();
$form['email'] = array(
'#title' => 'Owner Email',
'#type' => 'textfield',
);
$form['password'] = array(
'#title' => 'Password',
'#type' => 'password',
);
$form['csvfile'] = array(
'#title' => 'CSV File',
'#type' => 'file',
);
$form['submit'] = array(
'#value' => 'Upload',
'#type' => 'submit',
);
$form_state['rebuild'] = TRUE;
$form_state['redirect'] = FALSE;
return $form;
}
function mymodule_form_bulkupload_submit($form, &$form_state) {
dsm($form_state);
dsm($_FILES);
$data = $form_state['values']['csvfile'];
// With the unmanaged file we just get a filename back.
$filename = file_unmanaged_save_data($data, NULL, FILE_EXISTS_REPLACE);
if ($filename) {
$url = file_create_url($filename);
$_SESSION['file_example_default_file'] = $filename;
drupal_set_message(
t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)',
array(
'%filename' => $filename,
'@uri' => $filename,
'!url' => l(t('this URL'), $url),
)
)
);
}
else {
drupal_set_message(t('Failed to save the file'), 'error');
}
}