Saturday, January 2, 2016

Uploading Multiple Files Using Coldfusion, HTML5-style

You know how to upload a file with coldfusion. Add an file input tag to form, make sure the form encytype is "multipart/form-data", and then use cffile. Easy.

Ok, now what if you want to upload an arbitrary number of files? You could just show them more inputs, but HTML5 added the very nice multiple attribute to the file input tag, allowing a user to select more than one file at a time.

Sadly, ColdFusion never really supported it. Until now, that is.

Yes, dear reader, I have cracked the code. This is why I was delving into the inner workings of the form object before. I knew the information I needed was had to be accessible somewhere, it was just a matter of finding out where. I've packaged up the functionality and published it at GitHub, ready for you to use yourself.

Usage is easy. Make sure that you have the multiple attribute on your form's file upload field.
<input name="fieldname" type="file" multiple="multiple" />

Then, on the page that receives the form submission, make the following function call:

uploadedFiles = UploadMultipleFiles("fieldname", directoryToUploadTo)

The function will return an array of the paths to the newly uploaded files.

7 comments:

  1. Why is there no "cffile action="uploadall" somewhere in your code ?

    ReplyDelete
  2. I mixed your script with this one: http://www.w3bees.com/2013/12/multiple-file-upload-with-progress-bar.html
    This gives very good results. Can you improve your code to check the MIME type / extensions of the file ?

    ReplyDelete
  3. I did not use uploadAll because it does not fit my use case, which involves different file input fields, each of which must be handled differently.

    It could be extended pretty easily to reject files of the wrong type. I may patch it with that when I get a spare moment.

    ReplyDelete
  4. Thanks a ton!!! And it's very sad to know that ACF is not supporting such a great feature of HTML5 rather than wasting time on some unnecessary things.

    ReplyDelete
  5. Very nice!
    Will your code work with documents uploaded via the jQuery-File-Upload/?
    https://blueimp.github.io/jQuery-File-Upload/

    ReplyDelete