如何在 Struts 2 中上传多个文件

How to upload multiple files in Struts 2

我有一个 JavaScript 可以将多个文件上传到我的画廊系统。

单击按钮 start upload 时,它会在 Struts 的 Action class 中调用多个线程到我的方法 2.

在这种方法中,我需要验证我的图库系统是否有 space 来接受文件(为此我使用了一个业务对象,然后是一个 DAO class)。

但是我的问题是:

当我这样做时,我的操作线程几乎同时执行验证,但是如果一个线程没有完成上传,那么其他线程的大小就会不正确。

如何在Struts2中进行多文件上传?

The Struts 2 framework provides built-in support for processing file uploads that conform to RFC 1867.

您不需要使用多个 requests/threads 来上传多个文件。每个请求都作为单个文件上传处理,同时使用 Web 服务器的线程池。服务器根据来自任何客户端的请求选择一个线程。因此,如果您通过单个文件上传来上传多个文件,则无法控制处理所有文件所需的 space。任何单个文件上传都可能因系统无法接受文件而失败,与特定客户端无关。

如果您需要一次上传所有多个文件,那么您应该使用 Multiple File Uploading

As mentioned in the previous section one technique for uploading multiple files would be to simply have multiple form input elements of type file all with different names. This would require a number of setter methods that was equal to 3 times the number of files being uploaded. Another option is to use Arrays or java.util.Lists.


您可以配置fileUpload interceptor来限制上传文件的大小

maximumSize (optional) - the maximum size (in bytes) that the interceptor will allow a file reference to be set on the action. Note, this is not related to the various properties found in struts.properties. Default to approximately 2MB.


然后您可以配置从拦截器返回的自定义消息。

This interceptor will add several field errors, assuming that the action implements ValidationAware. These error messages are based on several i18n values stored in struts-messages.properties, a default i18n file processed for all i18n requests. You can override the text of these messages by providing text for the following keys:

  • struts.messages.error.uploading - a general error that occurs when the file could not be uploaded

  • struts.messages.error.file.too.large - occurs when the uploaded file is too large

  • struts.messages.error.content.type.not.allowed - occurs when the uploaded file does not match the expected content types specified

  • struts.messages.error.file.extension.not.allowed - occurs when the uploaded file does not match the expected file extensions specified


单个请求上传多个文件。要控制请求的总大小,您可以使用常量或 属性 struts.multipart.maxSize。例如,常量将每个请求的限制设置为 1M。

<constant name="struts.multipart.maxSize" value="1000000" />