Valid extensions for the upload field on Drupal 7
I need to make a form to upload a CSV file. I get the following error when I try to use the form item below:
Only files with the following extensions are allowed: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp.
$form['data_file'] = array(
'#type' => 'file',
'#title' => t('Data File'),
'#description' => t('CSV file to upload.'),
'#upload_validators' => array(
'file_validate_extensions' => array('csv'),
'file_validate_size' => array开发者_Go百科(32*1024*1024),
),
);
How can I let a CSV file pass through the validator?
I was able to do it with the following code in the form validation hook.
function mymodule_myform_validate($form, $form_state) {
$validators = array('file_validate_extensions' => array('csv'));
$file = file_save_upload('zipdata_file', $validators);
...
}
If you look at The forms API reference this comment explains how to do it.
I can't exactly test it out, but possibly something like this
$form['data_file'] = array(
'#type' => 'file',
'#title' => t('Data File'),
'#description' => t('CSV file to upload.'),
'#upload_validators' => array(
'file_validate_extensions' => array(0 => 'csv'),
'file_validate_size' => array(32*1024*1024),
),
);
Your form function
// don't forget this line
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['container']['csv_file'] = array(
'#type' => 'file' ,
'#title' => t('csv FILE') ,
'#description' => t('insert your csv file here') ,
) ;
Your validate function
function _your_function_validate($form, $form_state) {
$extensions = 'csv' ;
$validators = array(
'file_validate_extensions' => array($extensions),
);
// if the file not uploaded or the extension is wrong set error
if(!file_save_upload('csv_file', $validators)) { // cvs_file is the form name
form_set_error('csv_file', 'Please select the csv file') ;
}else{
// now the form is uploaded lets make another validation for extension
$file = file_save_upload('csv_file', $validators, file_directory_path()) ;
// another validator for the extension
if($file->filemime != 'text/csv' ) {
form_set_error('csv_file', 'Extensions Allowed : csv') ;
}
}
}
精彩评论