Struts2 上传文件,在发送文件之前验证文件大小和内容类型文件



我对 Struts 2 及其文件上传拦截器有问题。它已验证我的内容类型和文件大小,但上传过程不会停止。例如,我的上传限制是 2Mb,用户发送一个 500MB 的文件,拦截器 struts 2 记录该文件太大,但继续上传文件

我想在错误的情况下停止上传过程,因为 struts2 只有在发送文件完成后才会返回到我的页面。

谢谢

你不能在 Struts 中 - 因为 Struts 不会在你的 servlet 容器完成处理之前获取响应对象。

但是 - 大多数容器都有控制上传文件大小的方法,对于 tomcat,这是 maxPostSize 参数(默认值为 2GB) - 据我所知,tomcat 将计算传入字节数,然后在超过此值时退出。 即 Tomcat 不会继续读取超过 maxPostSize。其他容器将具有类似的配置参数。我从未使用过它,所以我在这里无法提供任何进一步的帮助。

如果您有嵌套的容器/服务(例如,位于Apache Web服务器后面的tomcat),请确保配置正确的容器/服务。

你可以。试试这个。它有效..

<action name="uploadDocs" class="com.test.myapp.UploadAction" method="upload">
    <interceptor-ref name="fileUpload">
        <param name="maximumSize">2097152</param> <!-- Max 2 MB limit per file-->
        <param name="allowedTypes">image/jpeg,image/bmp</param>
    </interceptor-ref>
    <interceptor-ref name="defaultStack"/>
    <interceptor-ref name="execAndWait"/>
        <param  name="delay">1000</param>
        <result name="wait">wait.jsp</result> <!-- display custom please wait page -->
    <result name="success">cmresulttemp.jsp</result>
    <result name="input">attachfiles.jsp</result>
    <result name="error">attachfiles.jsp</result>
</action>

如果要限制上传的总内容大小(不是每个文件),请在 struts.xml 文件的顶部添加此

内容
<constant name="struts.multipart.maxSize" value="10485760" /> <!-- Total 10 MB-->

最新更新