Struts2 文件上传示例

2025年3月17日 | 阅读 3 分钟

fileUpload 拦截器会自动处理所有包含文件的请求。

我们可以使用这个拦截器来控制 struts2 中的文件上传,例如定义允许的类型、最大文件大小等。

fileupload 拦截器的参数

为 fileupload 拦截器定义了 2 个参数。

参数描述
maximumSize指定要上传的文件的最大大小。
allowedTypes指定允许的类型。它可以是 image/png, image/jpg 等。

自动添加的参数

它会自动在请求中添加 2 个参数

  1. String fileName 表示文件的文件名。
  2. String contentType 指定文件的内容类型。

fileName 和 contentType 的名称取决于文件的请求参数。如果文件名是 file,您需要使用 fileFileName 和 fileContentType。如果文件名是 userImage,您需要在 Action 类中使用 userImageFileName 和 userImageContentType。


使用 struts 2 的图像上传示例

让我们看看文件上传应用程序的目录结构

file upload in struts 2 directory structure

1) 创建 UserImage.jsp

此 jsp 页面使用 struts UI 标签创建一个表单。它从用户那里接收文件。

index.jsp

2) 创建 SuccessUserImage.jsp

此 jsp 页面使用 struts UI 标签创建一个表单。它接收用户的姓名、密码和电子邮件 ID。

SuccessUserImage.jsp

3) 创建 action 类

此 action 类继承 ActionSupport 类并覆盖 execute 方法。

RegisterAction.java

4) 创建 struts.xml

此 xml 文件通过名称 input 定义了一个额外的结果,并定义了一个拦截器 jsonValidatorWorkflowStack。

struts.xml


输出

struts file upload example 1 struts 2 file upload example 2

图像不会显示在当前项目中。请访问服务器控制台中打印的图像位置以查看图像。