Reading time: 1 mins

Drupal 7 – Handling file uploads – allowed file extensions

While working with custom forms with file upload fields in drupal, you may sometimes get a error regarding extensions:

The specified file “your file name here” could not be uploaded. Only files with the following extensions are allowed: “jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp”

To allow all extensions, you have to manually set the ‘file_validate_extensions’ validator to an empty array.

$validators = array('file_validate_extensions' => array());
$file = file_save_upload('upload', $validators);


You can add the extensions to the array if you have certain number of extensions u want to allow.


$validators = array('file_validate_extensions' => array('jpg','gif','png'));

This will allow the user to upload only jpg/gif/png files.

For more information, check out Drupal API’s documentation at http://api.drupal.org/api/drupal/includes–file.inc/function/file_save_upload/7

The bare requirements for a file upload form is the “multipart/form-data” enctype, a “file” field, and the standard “submit” button. An example of a basic structure:

$form ['upload'] = array (
'#type' => 'file',
'#title' => 'Choose file',
'#description' => 'Upload a file.' );
$form ['submit'] = array ('#type' => 'submit', '#value' => t ( 'Submit' ) );
$form ['#attributes'] = array ('enctype' => "multipart/form-data" );

Dom PDF – Images dont get displayed
Drupal – Force Path Prefix for Default Language
© 2023 Anil Maharjan