开发者

Limit upload file action only for custom file extension using struts2

开发者 https://www.devze.com 2023-04-04 20:13 出处:网络
I want to restrict the file upload action only for files with .key extension in Struts2. If I set filetype to application/octet-stream in fileUpload interceptor in struts.xml than it allows to upload

I want to restrict the file upload action only for files with .key extension in Struts2. If I set filetype to application/octet-stream in fileUpload interceptor in struts.xml than it allows to upload all files with above content type without considering the extension but my requiremen开发者_StackOverflow中文版t is to limit the extension to .key.


There are two ways by which you can achieve the above goal. declarative and programmatically, To declaratively limit the file type a comma separated list of allowedTypes can be specified as a fileUpload interceptor param

<action name="fileUpload" class="com.example.UploadAction">
    <interceptor-ref name="basicStack"/>
    <interceptor-ref name="fileUpload">
        <param name="allowedTypes"></param>
    </interceptor-ref> 
    <interceptor-ref name="validation"/>
    <interceptor-ref name="workflow"/>

    <result name="success"</result>
</action>

more flexible way which avoid the need to configure Interceptor is to check it in programmatic way Programmatically limiting the file type means using the information passed in to your Action class via the setXContentType(String contentType) method.


I have got the answer. You need to use a another param type called "allowedExtensions" into fileUpload interceptor. Enter all the extension you are willing to allow in comma separated values. You can also add your custom messages for the specific error as well. Please refer Struts official site for file upload interceptor. Below is the syntax.

<interceptor-ref name="fileUpload">
    <param name="allowedExtensions">key</param>
</interceptor-ref> 
0

精彩评论

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

关注公众号