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
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
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...