The Muffin Man
The Muffin Man

Reputation: 20004

How to handle cffile specific errors in ColdFusion

I'm using a cffile tag with the accept attribute. If the user uploads a mime type other than what I have allowed I want to prevent it but at the same time I want to be able to handle the error. I tried using a try catch block but it still errors.

<cftry>
  <cffile action="upload"
          filefield = "txtImg"
          accept="image/jpeg, image/png, image/bmp, image/gif, image/pjpeg, image/x-png"
          destination="E:\www2\website\Home\uploads\Images\"
          nameconflict="makeunique">
    <cfcatch>
        <script>
            $(function(){ 
                alert("Only the following file types are allowed: .jpg, .gif, .bmp, .png.");
            });
        </script>
    </cfcatch>
  </cftry>  

Upvotes: 1

Views: 4358

Answers (2)

MPaul
MPaul

Reputation: 2733

You can also use:

<cfcatch>
    <cfif IsDefined("cfcatch.MimeType")>
        <!--- Do stuff --->
    </cfif>
</cfcatch>

Typically when defining the accept attribute of the <cffile> component it will raise a custom error of type MimeType.

Alternatively you can use a <cfcatch> for only MimeType errors.

<cfcatch type="MimeType">
    <!--- Do stuff --->
</cfcatch>

Upvotes: 0

Sergey Galashyn
Sergey Galashyn

Reputation: 6956

You have to analyze the cfcatch message. Slightly modified version of your code sample may look like this:

<cftry>

    <cffile action="upload"
        filefield = "txtImg"
        accept="image/jpeg, image/png, image/bmp, image/gif, image/pjpeg, image/x-png"
        destination="/tmp/"
        nameconflict="makeunique"/ >

    <cfcatch>

        <cfif FindNoCase("not accepted", cfcatch.Message)>
            <script>
                $(function(){
                    alert("Only the following file types are allowed: .jpg, .gif, .bmp, .png.");
                });
            </script>
            <cfabort />
        <cfelse>
            <!--- looks like non-MIME error, handle separately --->
            <cfdump var="#cfcatch#" abort />
        </cfif>

    </cfcatch>

</cftry>

Please note that I'm not sure about exact message thrown for incorrect mime type for all CF versions, so I've used a search by message chunk from ACF9 which looks like this: The MIME type of the uploaded file application/octet-stream was not accepted by the server.

Upvotes: 2

Related Questions