Multiple file upload usind Drupal 7 Form API

  • 4 September 2013
  • mohit.aghera

Some days ago I was working with very strange situation. I was implementing the multiple file upload. I googled it and found many solution like plupload and html5 upload any many more…

But I was curious whether can I implement with drupal form API or not. After digging little bit what I found was really interesting and awesome solution. Though I implemented using plupload but this solution using Drupal Form API is too good..

Here is how I achieved it..

I was integrating it in filedepot module, and in this module file upload is handled by the custom Ctools file upload form, so i have to do it by programatically.

If you are building using contetnt types then file field widget itself provides the functions to upload the multiple files.

I was building a module using the custom form. So I have written hook_form to create the form. Below snippet will generate the form.

function multifile_upload_form($form, &$form_state) {

      $form = array();


      $form['file'] = array(

            '#type' => 'file',

            '#name' => 'files[]',

            '#title' => t('Upload some multifile'),

            '#description' => t('You are allow to upload jpg, jpeg, png and gif, 10MB Max Size'),

            '#attributes' => array('multiple' => 'multiple'),

      );

      $form['submit'] = array(

            '#type' => 'submit',

            '#value' => t('Upload'),

      );

      return $form;

}

In the above $form Array notice the #attributes element. The '#attributies' field in the file field is what allows most browsers to recognize that this field will allow multiple file uploads at once. As far as I have tested it will work on ie 10, and all latest chrome, safari and firefox browsers.

Here I have taken name of file field as an array (files[]) instead of norman variable name. This will group all of your files in the $_FILES variable on form submit so that you can reference them as you'll see below.

Now I have implemented validate function.

function multifile_upload_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://')) {

                        $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.'));

            }

      }

}

In this validation function we are validating the files according the our specific criteria. You can change it later as per your requirements.

Notice that I'm using $i in file_save_load() function. Instead of the form file field shown in the first form function. This is because when you specify the '#name' of the file field as an array it will reference all uploaded files in the $FILES variable as numbered (from zero) indexes instead of string names. This is what allows us to save each file in the $FILES array.

function multifile_upload_form_submit($form, &$form_state) {

      if (is_array($form_state['values']['file'])) {

            //Make sure we keep our previously uploaded images

            foreach ($form_state['values']['file'] as $file) {

                  $new_file = file_load($file->fid);

                 

                  // Fetch the various parameters of the images like height, width etc..

                  // Though this is not required on case of other files you can straight away neglect it.

                  $file_info = image_get_info($file->uri);

                 

                  // Here you will get an individual file object.

                  // You can now manipulate as per your requirement and attach with nodes too.

            }

      }

      drupal_set_message(t('Upload successful'));

}

Now there is submit function, that will submit the form and you can manipulate the files according to your use case…

You are done with multiple file upload using Drupal Form API

I have tested it on ie10 and above and chrome 29.x, safari  5.x and firefox 23.x

 

Tags: 

Comments

Tfile's picture

I'm extremely impressed with your writing skills and also with the layout on your weblog.
Is this a paid theme or did you modify it yourself? Either way
keep up the excellent quality writing, it is rare to
see a nice blog like this one today.

Here is my page ... [url=http://tfile.me]Tfile[/url]

Jan Filein's picture

Nice solution! If I knew this solution before... :-)

I was so desperate that I have given up on their file API and started using SForms. It is simple and it had exactly what I wanted...

But building own solution would be definitelly more rewarding. ;-) Thanks for posting this code.

Sav's picture

Nice solution. Though, this example would not work if you change the input name from <code>files[]</code> to something else. That's mainly because <code>file_save_upload</code> function internally checks for the <code>files</code> variable. 

By the way, I believe it would be better for various purposes implementing a disqus instead of a custom (or drupal) comment plugin :)

Keep up the good work!

Wonderful post but I was wanting to know iif you could write
a litte more on this topic? I'd be very thankful if you could elaborate a little bit
further. Many thanks!

vinoth's picture

Hi I used this code and it uploads only one image cant upload multiple images.. give me a solution.. Iam also using drupal7.

mohit.aghera's picture

Thanks for visit,

Are you using this code for the filedepot file upload or the drupal's default forms.

Actually i had modified this  for the filedepot module only, still i will check and let you know for the drupal's forms.

Namita's picture

Only solution I was able to find for multiple upload is yours and can please direct me in right direction that how can I use this solution for uploading multiple files through FILE DEPOT.

Any help will be really appreciated.

mohit.aghera's picture

You are not able to get how to implement or facing any issue in implementation ?

Basically you have to create a simple hook_form_alter() only..

Houston's picture

I want to to thank you for this very good read!! I absolutely enjoyed
every little bit of it. I've got you bookmarked to check out
new stuff you post…

nice's picture

Hello ,

You decribed nice tutorial, but this is simple file upload , this  is not working multiple file upload at a time. so can u please elaborate for the multiple file upload through custom coding

ksp's picture

Elegant soultion ... Thanks a ton.. saved my day.. had been loking for the solution from 2 days..

Nice blog here! Also your website loads up fast!
What web host are you using? Can I get your affiliate link
to your host? I wish my web site loaded up as fast as yours lol

Hussain's picture

Wow ...

it works like a charm !!

 

thanks a trillion 

kavya's picture

Hi Mohit,
Iam facing issues with few functionalities such as pagination,pie-charts etc.
Im new to drupal and PHP.
Can I get ur contact id so that I can expain the issue in detail

Thanks in advance

You decribed nice tutorial, but this is simple computer file publish , this  is not working several computer file publish at a time. so can u please elaborate for the several computer file publish through custom coding

Add new comment