1. 程式人生 > >struts2學習筆記十五(第15講.Struts2的檔案上傳和下載續三)

struts2學習筆記十五(第15講.Struts2的檔案上傳和下載續三)

[/code][b][size=xx-large]Struts2的檔案上傳和下載續三[/size][/b]
[color=red]功能:[/color]使用者可以自定義上傳檔案的個數,如果新增的個數多了的話,還可以進行刪減。
一、修改之前根目錄下的upload.jsp檔案:
[code="Jsp"]
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>

<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.removeChild(input);
td.removeChild(button);
}

td.appendChild(br);
td.appendChild(input);
td.appendChild(button);
}

</script>

</head>

<body>

<s:form action="upload" theme="simple" enctype="multipart/form-data" method="post">

<table align="center" width="40%" border="1">
<tr>
<td>username</td>
<td>
<s:textfield name="username" ></s:textfield>
</td>
</tr>
<tr>
<td>password</td>
<td>
<s:password name="password" ></s:password>
</td>
</tr>

<tr>
<td>file</td>
<td id="more">
<s:file name="file"></s:file><input type="button" value="Add More..." onclick="addMore()">
</td>
</tr>


<tr><td><s:submit value=" submit "></s:submit></td>
<td>
<s:reset value=" reset "></s:reset>
</td>
</tr>
</table>
</s:form>

</body>
</html>

二、伺服器端uploadAction.java(在src/com.test.action下)中的程式碼不需要進行修改,以為之前用的就是List型別的。
[color=red]功能:[/color]實現上傳檔案的型別約束。
三、1、修改struts.xml檔案,修改action的屬性:
<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>
<param name="allowedTypes">application/vnd.ms-powerpoint</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>

2、在upload.jsp頁面列印提示錯誤資訊,新增程式碼:
<table align="center" width="40%">
<tr>
<td>
<s:fielderror cssStyle="color:red"/>
</td>
</tr>
</table>

3、在提示檔案資訊com.test.util裡面的message.properties新增自定義的提示資訊:
struts.messages.error.content.type.not.allowed=\u4e0a\u4f20\u6587\u4ef6\u7c7b\u578b\u4e0d\u5141\u8bb8\uff0c\u8bf7\u91cd\u8bd5\uff01
struts.messages.error.file.too.large=\u4e0a\u4f20\u6587\u4ef6\u8fc7\u5927\uff0c\u8bf7\u91cd\u8bd5\uff01

四、檔案的下載功能:
(待續)