0

I am working multi file upload functionality with different extensions(pdf,doc,png,jpg). Following code is working fine for multiple images upload. I would like to know how this code modify for different extension like doc, pdf, png,gif etc.

function mymodule_form($form, &$form_state) {
    $form['file'] = array(
        '#type' => 'file',
        '#name' => 'files[]',
        '#title' => t('Upload some photos'),
        '#attributes' => array('multiple' => 'multiple'),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),

    );
}

form mymodule_form_validate($form, &$form_state) {
    //Save multiple files
    $num_files = count($_FILES['files']['name']);
    for ($i = 0; $i < $num_files; $i++) {
        $file = file_save_upload($i, array(
            'file_validate_is_image' => array(),
            'file_validate_extensions' => array('png gif jpg jpeg'),
        ));
        if ($file) {
            if ($file = file_move($file, 'public://images')) {
                $form_state['values']['file'][$i] = $file;
            }
            else {
                form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
            }
        }
        else {
            form_set_error('file', t('No file was uploaded.'));
        }   
    }
}
1

You can use '#type' => 'managed_file' instead of '#type' => 'file'

managed_file types is powerful tools support any kind of files format with ajax upload.

example :
$form['file'] = array( '#type' => 'managed_file', '#name' => 'files[]', '#title' => t('Upload some photos'), '#attributes' => array('multiple' => 'multiple'), ); you can also add upload location of files like

'#upload_location' => 'public://myfiles/'

for more info. https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#managed_file

| improve this answer | |
0

In your validation function you have added file_validate_is_image. This function returns an array. If the file is not an image, it will contain an error message that's why you are unable to add other extensions except images.

You have to remove it (file_validate_is_image) and try again.

'file_validate_extensions' => array('png gif jpg jpeg pdf doc'), //add different extensions whatever you would like to.
| improve this answer | |

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.