Drupal 7 – Handling file uploads – allowed file extensions

13 years ago, October 14, 2011
Reading time: 1 mins

While working with custom forms with file upload fields in Drupal, you may sometimes get an 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.

E.g.

$validators = array('file_validate_extensions' => array());

$file = file_save_upload('upload', $validators);

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

E.g.

$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" );
Previous
Dom PDF – Images dont get displayed
Next
Drupal – Force Path Prefix for Default Language
© 2024 Anil Maharjan