1

I've got a module that let users upload files, and everything works as long as the files are in the standard array of allowed extensions. I've tried using file_validate_extensions(), but this doesn't seem to change anything.

This is the code I'm using to upload now (the docx extension is added to the standard allowed ones, but it doesn't seem to get picked up):

$fid = $form_state['values']['attachment'];
$file = file_load($fid);

if ($file != null) {
  file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
}
  • 1
    Hello, Slyder; welcome on Drupal Answers. This is not the answer to your question, but you are not using the value returned from file_validate_extensions(); as the function just checks if the extension is one of the extensions contained in the string passed as argument, and it returns an array containing an error string, if you don't use the returned value is perfectly useless to call the function. – kiamlaluno May 7 '11 at 17:09
2

You actually have to check for the return values of the file_validate_extensions() function in order to detect if any errors have occurred.

so your code would be something like this:

$fid = $form_state['values']['attachment'];
$file = file_load($fid);

if ($file != null) {
  $extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");
  if (!$extension_errors) {
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  } else form_set_error('attachment',$extension_errors[0]);
}
0

I think what you are looking for is here

drupal-7-handling-file-uploads

Drupal 7 forms API: File not uploading

I too have tried with below form and it worked for me

function video_upload_subtitles_form($form, &$form_state) {
     $form['sub_file'] = array(
            '#type' => 'file',
            '#title' => t('Upload video'),
            '#description' => t('Pick a video file to upload.'),
        );

}
function video_upload_subtitles_form_submit($form, &$form_state) {
 $validators = array('file_validate_extensions' => array());
 $file = file_save_upload('sub_file', $validators, "public://");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.