Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Multiple-File Uploads with ColdFusion

Letting users pick whatever files they want to upload and then pushing them all at once

One task that arises again and again in ColdFusion application development is the need for users to be able to upload multiple files to the Web Server. Back in the stone ages (and by this I mean more than a couple of years ago) we had a limited set of options to be able to do this. Usually a problem such as this was approached using one of three means.

Perhaps most crudely, the user would be able to load a file at a time. And if they needed to upload 10 files, that meant 10 round trips to the server and a heck of a lot of clicks. To paraphrase Hal Helms who, I believe, was paraphrasing someone else, this can create a disorder known as Post Back Traumatic Stress Syndrome.

To add a level of elegance, some of us began prompting the user ahead of time: "How many files do you want to upload?" This would be followed by an ugly page with rows and rows of file-type input boxes. And what if the user changed his mind about how many files? Well, he can always start over.

And sometimes we'd just take the approach of "knowing" that the user wouldn't need to upload more than x number of files, so we would just put x number of input boxes on a page, and they could use as many as they needed...unless of course they needed more, in which case they could just repeat the process.

What is the common thread here? While each of these are indeed functional approaches, none of them provides the level of user experience that our users are beginning to expect in Web applications thanks to the growing implementation of rich JavaScript libraries, AJAX, and various RIA technologies.

Wouldn't it be nice if there were some free tool that lets you give your users the ability to choose whatever files they want to upload and then push them all at once?
Well, yes, it would and thankfully there is such a tool written by a developer who simply goes by the name Stickman as in www.the-stickman.com. This tool lets you quite easily allow users to upload multiple files using a single-file input element. Once users have added files to a queue they can then push them all at once. If you're familiar with adding attachments in Gmail you know this concept well. We're going to provide a very simplified example and within a few minutes you can give your user an interface as shown in Figure 1.

Let's look at a step-by-step approach for adding this to your site. First, we need to get the JavaScript file that makes this process so easy. To do this, we need to download the zip file at http://the-stickman.com/files/multiple-file-element.zip.
You'll find three files inside this zip file:

  • example.html - This HTML file is the of the ColdFusion example we're about to build.
  • multifile.js - The JavaScript library used by the HTML.
  • multifile_compressed.js - This file is functionally the same as the previous file, the difference being the overall size of the compressed file by removing white space.
For our example we'll place the last of the three, multifile_compressed.js, in our application's webroot.

The next step is completely superficial and is simply included to stylize the form just a bit, but we'll create a simple CSS file called uploader.css and put that in our webroot. If you're in a big hurry, you can skip this step without any consequences in running the uploader. However, if you want your output to look like the example here, your CSS file should contain the following shown in Figure 2.

Now it's time to make the form our users are going to use to upload files. The upload form template looks like this Figure 3.

As you can see in that code, we call the multifile_compressed.js file in the head of our document in addition to linking the CSS file we created. In the body, you find that our form has a single-file input element. This is used to add files to the upload queue. As files are added, the script actually adds new file-input elements and hides them by absolutely positioning them 1000px to the left of the top-left corner of the screen. The author took this approach as opposed to setting the style equal to "display:none" to allow compatibility with Safari browsers.

Once the new input element is added, the addListRow() JavaScript function is called that writes a new row in the "FileList" div element. By default this row displays the name of the new file and a button to remove it before form submission, but this function can be easily modified to make this display appear however you wish.

Now that we've created our form page, it's time to manage the action once the form is submitted. First, we should start by creating a directory to receive the uploaded files. In our example, we'll create a sub-directory in the webroot called "upload."

Next we have to write our action page. Create a new template in the webroot called "actUpload.cfm" and include the following code shown Figure 4.

So what exactly are we doing here? Let's walk through it.

First, and hopefully quite obviously, we are ensuring that a form submission has actually occurred to get us to this page. On any form post in ColdFusion when the method type is set to "post," there will be a variable "fieldnames" present in the form scope that is a list of the names of all the form elements that were passed to the action page. This multi-file uploader script creates fields that begin with the string "file_" and end with an incrementing value beginning with 0. There will always be one more element than the number of files that are being uploaded, and that element will be an empty string. For instance, when we upload three files we'll have: file_0, file_1, file_2, and then file_3, which is an empty value. So in the case of three submitted files, and assuming no other fields were present in the form, #forms.fieldnames# would output as: "FILE_0,FILE_1,FILE_2,FILE_3."

On line 2, we're creating a new array, which will be used later to house the results of each file upload.

Then we begin looping through our #form.fieldname# list. If the current element name begins with "file_" and the form variable isn't an empty string, we're going to attempt to upload this file to the server.

You can see in the <cffile/> tag that we're storing the results of the upload process in a variable called "ThisFile." We then append that result structure to our UploadedFiles array. Once we're done, we simply dump the array to the screen. In an actual production scenario, you'd obviously want to trap more errors and probably do something more intelligent with the results of the uploads before redirecting the user to a confirmation page.

Providing your user with tools such as this can affect their overall perception of your site, and subtle things such as this can really boost their "feel good" factor. While there are other ways to achieve the same results, such as the commercially licensed CF_ProFlashUpload, or various other homegrown concoctions, Sickman's multiple-file element uploader is a quick, easy, and flexible choice.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
Early Bird Registration Discount Expires on August 31, 2018 Conference Registration Link ▸ HERE. Pick from all 200 sessions in all 10 tracks, plus 22 Keynotes & General Sessions! Lunch is served two days. EXPIRES AUGUST 31, 2018. Ticket prices: ($1,295-Aug 31) ($1,495-Oct 31) ($1,995-Nov 12) ($2,500-Walk-in)
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...