此注册表单包含文件上传和文本字段。使用Struts2我们如何提交表单参数并上传文件?
1. register.jsp
:
<s:form action = "Register" enctype="multipart/form-data" method="post">
<s:textfield name="uname" label = "User Name"/>
<s:password name ="password" label = "Password"/>
<s:file name="fileUpload" label="Select a File to upload" size="40" />
<s:submit/>
</s:form>
2。 RegisterAction
:
package user.action;
import java.io.File;
public class RegisterAction
{
private String uname,password;
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
//getter setters
public String execute() throws Exception
{
return "success";
}
}
3。 struts.xml
:
</action>
<action name="Register" class="user.action.RegisterAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">text/plain</param>
<param name="maximumSize">10240</param>
</interceptor-ref>
<result name="success">registered.jsp</result>
</action>
4. registered.jsp
:
User Name : <s:property value="uname"/>
File Name : <s:property value="fileUploadFileName"/>
Content Type : <s:property value="fileUploadContentType"/>
File : <s:property value="fileUpload"/>
用户名<s:property value="uname"/>
没有给出任何输出
registered.jsp
.我们是否应该使用 Apache 文件上传来解析请求以获取文本字段值?
最佳答案
不,你不应该。 Apache 文件上传是Struts2 的一部分。 fileUpload
拦截器已包含在 defaultStack
中,因此您无需在操作配置中引用它。如果你想覆盖这个拦截器的参数,那么
<action name="Register" class="user.action.RegisterAction">
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedTypes">text/plain</param>
<param name="fileUpload.maximumSize">10240</param>
</interceptor-ref>
<result name="success">registered.jsp</result>
</action>
As long as the required libraries are added to your project you will be able to take advantage of of the Struts 2 fileUpload capability.
关于java - 如何使用 Struts2 提交带有文件和文本字段的多部分/表单数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27349716/