With CF8 and compatible:
<cffunction name="IsRtfFile" returntype="Boolean" output="false"> <cfargument name="FileName" type="String" /> <cfreturn Left(FileRead(Arguments.FileName),5) EQ '{\rtf' /> </cffunction>
For earlier versions:
<cffunction name="IsRtfFile" returntype="Boolean" output="false"> <cfargument name="FileName" type="String" /> <cfset var FileData = 0 /> <cffile variable="FileData" action="read" file="#Arguments.FileName#" /> <cfreturn Left(FileData,5) EQ '{\rtf' /> </cffunction>
Update: Best CF8 / compatible answer. In order not to load the entire file into memory, you can do the following to load only the first few characters:
<cffunction name="IsRtfFile" returntype="Boolean" output="false"> <cfargument name="FileName" type="String" /> <cfset var FileData = 0 /> <cfloop index="FileData" file="#Arguments.FileName#" characters="5"> <cfbreak/> </cfloop> <cfreturn FileData EQ '{\rtf' /> </cffunction>
Based on the comments:
Here's a very quick way how you can generate a βwhat format is thisβ type of function. Not perfect, but it gives you an idea ...
<cffunction name="determineFileFormat" returntype="String" output="false" hint="Determines format of file based on header of the file data." > <cfargument name="FileName" type="String"/> <cfset var FileData = 0 /> <cfset var CurFormat = 0 /> <cfset var MaxBytes = 8 /> <cfset var Formats = { WordNew : 'D0,CF,11,E0,A1,B1,1A,E1' , WordBeta : '0E,11,FC,0D,D0,CF,11,E0' , Rtf : '7B,5C,72,74,66' <!--- {\rtf ---> , Jpeg : 'FF,D8' }/> <cfloop index="FileData" file="#Arguments.FileName#" characters="#MaxBytes#"> <cfbreak/> </cfloop> <cfloop item="CurFormat" collection="#Formats#"> <cfif Left( FileData , ListLen(Formats[CurFormat]) ) EQ convertToText(Formats[CurFormat]) > <cfreturn CurFormat /> </cfif> </cfloop> <cfreturn "Unknown"/> </cffunction> <cffunction name="convertToText" returntype="String" output="false"> <cfargument name="HexList" type="String" /> <cfset var Result = "" /> <cfset var CurItem = 0 /> <cfloop index="CurItem" list="#Arguments.HexList#"> <cfset Result &= Chr(InputBaseN(CurItem,16)) /> </cfloop> <cfreturn Result /> </cffunction>
Of course, it is worth noting that all this will not work with formats without headings, including many common text (CFM, CSS, JS, etc.).