开发者

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> 开发者_如何学编程 


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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜