Question

I have a custom form, with a field for the user to upload an image file (their logo). In the form validate hook, I've implemented file_save_upload, which is continually returning false. I can see that the file is in fact being saved in the correct location on upload, so why isn't file_save_upload working?

The form field:

 $form['company_logo'] = array(
  '#type' => 'managed_file',
  '#title' => t('Company Logo'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#upload_location' => 'public://uploads/',
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    //'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),
);

The validation hook:

    $file = file_save_upload( 'company_logo' , array(),  'public://uploads/', FILE_EXISTS_RENAME);
   if (!$file) {
      form_set_error('company_logo', t('Unable to access file or file is missing.'));
   }
Was it helpful?

Solution

The managed file element handles moving the uploaded file for you, so there's no need to call file_save_upload() manually.

You're getting a NULL return because of these lines in file_save_upload():

// Make sure there's an upload to process.
if (empty($_FILES['files']['name'][$source])) {
  return NULL;
}

As the file's already been processed there's nothing for the function to do.

You can persist the file entry by adding a submit handler to the form and using code similar to

$file = file_load($form_state['values']['company_logo']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top