How to properly use Coldfusion's FileExist() method?

d.lanza38 picture d.lanza38 · Apr 30, 2012 · Viewed 13.8k times · Source

I don't use coldfusion much at all, I'm needed to patch up some code though. Basically I'm trying to check and see if a file I uploaded exist and if it does exist, increment a variable by 1. Then repeat untill I get a unique file name. For whatever reason I can't figure out the proper way to use FileExist(). Some forums suggest using it with len() but those are from 2006 and when I do that it seems to always come out true. Also, when I look at http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7c66.html it says it returns either Yes or No. I tried to check against the result various ways, but no luck.

This is the portion of code I have which I am dealing with. The application.filepath is just a variable in my application file which store the expandpath().

<cffile action="upload" destination="#Application.filePath#ListingsGallery/" filefield="iconImage" nameconflict="makeunique">
<cfset iconPlace = #cffile.serverfile#>
<cfset myExt = listLast(iconPlace,".")>
<cfset i = 1 >
<cfset myVar = false>
<cfloop condition="myVar EQ false">

    <cfset newIconName = "iconPhoto" & i &"."& myExt>
    <cfset iconName = Application.filePath & "ListingsGallery/" & #newIconName#>
<cfoutput>#iconName#</cfoutput><br />//just checking to see if it is the correct path, it is.

    <cfif FileExists(iconName) EQ 'Yes'>
         <cfoutput>#myVar#</cfoutput> //checking the value, it never hits here.
    <cfelse>
             <cfoutput>#myVar#</cfoutput><br /> //checking the value, it always hits here.
    <cfset myVar = true>        
             <cfoutput>#myVar#</cfoutput> //Again check the value.
    </cfif>
<cfset i++>
</cfloop>                     
<cffile action="rename" source="#Application.filePath#ListingsGallery/#iconPlace#" destination="#Application.filePath#ListingsGallery/#newIconName#">

The absolute path on a unix server is something like, /var/www/website folder name/ etc.... Correct? That's the absolute server path, the coldfusion docs seem to specify at least a microsoft absolute server path so I'm assuming this is what is needed.

Edit--------------------------- PS: I can' only give one of you credit, so I gave it to Kruger since he came a minute earlier. lol...

Answer

Evik James picture Evik James · Apr 30, 2012

FileExists() returns a boolean value. This should work fine now that the typo has been fixed:

<cfif fileExists(TheFile)>
  // do this
<cfelse>
  // do that
</cfif>