Handling and Storing File Names Uploaded in ColdFusion
With the advent of more sophisticated file systems came about the ability to name files with more than eight characters. In fact, we could have spaces and special characters! What a wondrous thing. It seems that with the popularity of the web, however, things kind of went backwards. Special characters, though can be dealt with using character codes, can be a pain in the back side, especially when serving them up to a viewer using a server side technology.
In this little article I will give some examples on how one can simply dodge these headaches by using a bit of regular expression magic in ColdFusion to simply say “NO” to spaces and special characters. For this example I will use a terrible name for a file. Let’s try “I’m a bad name for a file. This file name is dumb.jpg”. Extreme? Of course! Now, let’s strip that puppy down into parts. What we want, in the end, is a structure with the root file name and extension, useful for whatever your mind wishes to purpose.
The first task is to strip down the file name. We are going super simple here. Get rid of anything that isn’t a letter or number. We are also assuming a 2-4 digit extension. This will leave us with a clean file name plus extension.
-
<cfset fileInfo.filename = fileInfo.filename.replaceAll("(?i)(?!\.[a-z0-9]{2,4}$)[^a-z0-9]*", "") />
The next thing to do is grab the extension off of our pretty new file name.
-
<cfset fileInfo.extension = fileInfo.filename.replaceAll("(?i)([a-z0-9]+)(?=\.[a-z0-9]{2,4})", "") />
As a next step I go ahead and strip the extension off of the file name, giving you two pieces of information back in the result structure, a file name, and an extension.
-
<cfset fileInfo.filename = fileInfo.filename.replaceAll("(?i)(\.[a-z0-9]{2,4})(?![a-z0-9]+\.)", "") />
-
<cfset fileInfo.extension = mid(fileInfo.extension, 2, len(fileInfo.extension)) />
The result of all this is a structure with two fields: filename, and extension. Here is the entire function.
-
<cffunction name="cleanFileInformation" returntype="struct" access="public" output="false">
-
<cfargument name="filePath" type="string" required="true" />
-
-
<cfset var fileInfo = structNew() />
-
-
<cfset fileInfo.filename = getFileFromPath(arguments.filePath) />
-
<cfset fileInfo.filename = fileInfo.filename.replaceAll("(?i)(?!\.[a-z0-9]{2,4}$)[^a-z0-9]*", "") />
-
<cfset fileInfo.extension = fileInfo.filename.replaceAll("(?i)([a-z0-9]+)(?=\.[a-z0-9]{2,4})", "") />
-
-
<cfset fileInfo.filename = fileInfo.filename.replaceAll("(?i)(\.[a-z0-9]{2,4})(?![a-z0-9]+\.)", "") />
-
<cfset fileInfo.extension = mid(fileInfo.extension, 2, len(fileInfo.extension)) />
-
-
<cfreturn fileInfo />
-
</cffunction>
May 7th, 2008 at 2:35 pm
[...] Howdy peeps! New little article talking about cleaning up file names in ColdFusion, useful for when processing a file upload, for example. Check it out! [...]