用户可上传任意多个文件。
可以像上传邮件附件一样,当用户点add more按钮时添加一个新的文件上传控件。
还可以有remove按钮。
这须要采用js来完成。
upload.jsp
<script type="text/javascript">
function addMore() {
var td = document.getElementById("more");
var br = document.createElement("br"); //创建一些元素组件
var input = document.createElement("input")
var button = document.createElement("input")
input.type = "file"; //为这些组件设置属性
input.name="file"
button.type = "button";
button.value="Remove";
button.onclick = function() { //设置组件的事件方法
td.removeChild(br); //为td元素删除一些组件
td.removeChild(input);
td.removeChild(button);
}
td.appendChild(br); //为td这个元素添加一些组件
td.appendChild(input);
td.appendChild(button);
}
</script>
<s:fielderror cssStyle="color:red"/>
<table>
<tr>
<td id="more">
<s:file name="file"></s:file><input type="button" value="add more..." οnclick="addMore()">
</td>
</tr>
</table>
action参见上一篇
struts.xml
<action name="upload" class="com.test.action.UploadAction">
<result name="success">/uploadResult.jsp</result>
<result name="input">/upload.jsp</result>
<interceptor-ref name="fileUpload">
<param name="maximumSize">409600</param> //设置上action中上传文件的大小(4M)
<param name="allowedTypes">application/vnd.ms-powerpoint</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
文件类型的值可参见tomcat/conf/web.xml约1105行。
当上传文件的类型不符合时,会跳转到input页面上。
替换文件不匹配时struts2的默认错误信息。
src/message.properties中
struts.messages.error.content.type.not.allowed=...
struts.messages.error.file.too.large=...
struts.messages.error.uploading=... //此信息为其他的错误信息,如网络异常
struts.messages.removing.file=... //删除临时文件时错误信息
此key源自struts2-core.jar/org/apache/struts2/struts-messages.properties