我正在使用带有accept属性的cffile标记。如果用户上传的mime类型不是我允许的,我想要阻止它,但同时我希望能够处理错误。我尝试使用try catch块,但仍然存在错误。
<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>
答案 0 :(得分:2)
您必须分析cfcatch
消息。您的代码示例的略微修改版本可能如下所示:
<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>
请注意,我不确定所有CF版本的错误mime类型引发的确切消息,所以我使用了来自ACF9的消息块搜索,如下所示:The MIME type of the uploaded file application/octet-stream was not accepted by the server.
答案 1 :(得分:0)
您也可以使用:
<cfcatch>
<cfif IsDefined("cfcatch.MimeType")>
<!--- Do stuff --->
</cfif>
</cfcatch>
通常,在定义accept
组件的<cffile>
属性时,会引发MimeType
类型的自定义错误。
或者,您只能<cfcatch>
使用MimeType
错误。
<cfcatch type="MimeType">
<!--- Do stuff --->
</cfcatch>