When accepting uploads from a browser, it can sometimes be handy to have access to the filename before using CFFILE to “upload” the file onto the file system. For example say you want to show an error message if the file is not a PDF. In that case what I’ve usually done is use CFFILE to place the file onto the file system, and then check the extension. If its not in my allowed list, then I delete the file and send an error message to the client. But using the code below I can check the file extension without having to use CFFILE first. For example you could do something like this:

<cfset theClientFilename = getClientFileName("myFormField")>
<cfif ListLast(theClientFilename,".") NEQ "pdf">
   // do your error handling here
  // else the extension is ok. Use cffile to handle the upload and proceed

Here is the getClientFileName function, both in cfscript and regular tag formats.

function getClientFileName(fieldName) {
	var tmpPartsArray = Form.getPartsArray();
	var clientFileName = "";

	if (IsDefined("tmpPartsArray")) {
		for (local.tmpPart in tmpPartsArray) {
			if (local.tmpPart.isFile() AND local.tmpPart.getName() EQ arguments.fieldName) {
				return local.tmpPart.getFileName();
	return "";
<cffunction name="getClientFileName" returntype="string" output="false" hint="">
	<cfargument name="fieldName" required="true" type="string" hint="Name of the Form field" />

	<cfset var tmpPartsArray = Form.getPartsArray() />

	<cfif IsDefined("tmpPartsArray")>
		<cfloop array="#tmpPartsArray#" index="local.tmpPart">
			<cfif local.tmpPart.isFile() AND local.tmpPart.getName() EQ arguments.fieldName> 
				<cfreturn local.tmpPart.getFileName() />
	<cfreturn "" />

I wrote and tested this on CF10, but it will probably work all the way back to CF7. I tried this on Railo and it did not work, it errored on the getPartsArray() method. If you need to do this on Railo, this code will work (tested on 4.0.2): GetPageContext().formScope().getUploadResource("myFormField").getName()


  1. Tim Leach says:

    This is an awesome tip. Feels so much cleaner than the typical upload check delete, especially when trying to make your file uploads secure.

  2. Jake Churchill says:

    This is awesome. I gotta remember to try this.

  3. Mark says:

    Thanks so much!!! I’ve been trying to find a way to detect if a file was uploaded with a ‘?’ in the file name (which causes the cffile tag to error), and this is it! Now I can detect the question mark and modify the file save path to remove the question marks on a windows server!

Leave a Reply

You must be logged in to post a comment.