struts2實現文件的上傳和下載實例


實現原理

Struts 2是通過Commons FileUpload文件上傳。

Commons FileUpload通過將HTTP的數據保存到臨時文件夾,然后Struts使用fileUpload攔截器將文件綁定到Action的實例中。從而我們就能夠以本地文件方式的操作瀏覽器上傳的文件

具體實現:

一、創建index.jsp頁面

<body>
<s:form action="upload" method="post" theme="simple" enctype="multipart/form-data">
<table align="center" width="50%" border="1">
<tr>
<td>選擇上傳文件</td>
<td id="more">
<s:file name="file"></s:file>
<input type="button" value="Add More.." onclick="addMore()">
</td>
</tr>
<tr>
<td><s:submit type="button" value="submit" onclick="return checkf()"/></td>
<td><s:reset value="reset "></s:reset></td>
</tr>
</table>
<table align="center" width="50%" border="1">
<tr>
<td>測試.txt</td>
<td>
<a href="<s:url value='download.action'><s:param name='fileName'>測試.txt</s:param> </s:url>">下載</a>
</td>
</tr>
</table>
</s:form>
</body>

  

  創建result.jsp頁面

 1 <body>
 2 <s:form>
 3     <div style="border:1px solid black">成功上傳的文件:<br>
 4         <ul style="list-style-type:decimal">
 5     <s:iterator value="#request.fileName" id="file" status="status">
 6             <li><s:property/> </li>
 7     </s:iterator>
 8         </ul>
 9     </div>
10 </s:form>
11 </body>

當然別忘了在每個頁面上都添加上struts2 標簽引用<%@taglib prefix="s" uri="/struts-tags" %>

二、創建updown.js文件,在index.jsp中引用

 1 function checkf(){
 2     var files =    document.getElementsByName("file");
 3     if(files[0].value.length!=0){
 4             return true;
 5      }else{
 6         alert("請選擇文件");
 7         return false;
 8      }
 9 }
10 function addMore()
11 {
12    var td = document.getElementById("more");
13     var br = document.createElement("br");
14     var input = document.createElement("input");
15     var button = document.createElement("input");
16     input.type = "file";
17     input.name = "file";
18     button.type = "button";
19     button.value = "Remove";
20      button.onclick = function()
21     {
22         td.removeChild(br);
23         td.removeChild(input);
24         td.removeChild(button);
25     }
26       td.appendChild(br);
27     td.appendChild(input);
28     td.appendChild(button);
29 }

 

三、創建upDownloadAction.java

  1 package com.action;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.InputStream;
  8 import java.io.OutputStream;
  9 import java.io.UnsupportedEncodingException;
 10 import java.util.List;
 11 import javax.servlet.http.HttpServletRequest;
 14 import com.opensymphony.xwork2.ActionSupport;
 15 import org.apache.struts2.ServletActionContext;
 16 
 17 public class UpDownloadAction extends ActionSupport {
 18 
 19     private static final long serialVersionUID = 1L;
 20     private List<File> file;// 對應jsp中file標簽
 21     private List<String> fileFileName;//  
 22     private List<String> fileContentType;//  
 23     private String fileName;//獲得jsp中pram參數
 24     @SuppressWarnings("deprecation")
 25     // 文件上傳
 26     public String uploadFiile() throws Exception {
 27         String root = ServletActionContext.getServletContext().getRealPath(
 28                 "/upload");// 上傳路徑
 29         System.out.println(root);
 30         InputStream inputStream;
 31         File destFile;
 32         OutputStream os;
 33         for (int i = 0; i < file.size(); i++) {
 34             inputStream = new FileInputStream(file.get(i));
 35             destFile = new File(root, this.getFileFileName().get(i));
 36             os = new FileOutputStream(destFile);
 37             byte[] buffer = new byte[400];
 38             int length = 0;
 39             while ((length = inputStream.read(buffer)) > 0) {
 40                 os.write(buffer, 0, length);
 41             }
 42             inputStream.close();
 43             os.close();
 44         }
 45         HttpServletRequest request = ServletActionContext.getRequest();
 46         request.setAttribute("fileName", fileFileName);
 47         return SUCCESS;
 48     }
 49 
 50     // 文件下載
 51     public InputStream getDownloadFile() throws FileNotFoundException,
 52             UnsupportedEncodingException {
 53         System.out.println(getFileName());
 54 
 55         // 如果下載文件名為中文,進行字符編碼轉換
 56         ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="
 57                         + java.net.URLEncoder.encode(fileName, "UTF-8"));
 58         InputStream inputStream = new FileInputStream("F:/"  //使用絕對路徑 ,從該路徑下載“測試.txt"文件
 59                 + this.getFileName());
 60         System.out.println(inputStream);
 61         return inputStream;
 62     }
 63 
 64     // 下載
 65     public String downloadFile() throws Exception {
 66         return SUCCESS;
 67     }
 68 
 69     public String getFileName() throws UnsupportedEncodingException {
 70         return fileName;
 71     }
 72 
 73     public void setFileName(String fileName)
 74             throws UnsupportedEncodingException {
 75         this.fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8");
 76     }
 77  }

注:屬性的 get和set方法已省略。

四、最后是配置文件

1、web.xml配置

1     <filter>  
2         <filter-name>struts2</filter-name>  
3         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
4     </filter>  
5        
6     <filter-mapping>  
7         <filter-name>struts2</filter-name>  
8         <url-pattern>/*</url-pattern>  
9     </filter-mapping> 

2、struts.xml配置

 1 <struts>  
 2    <constant name="struts.i18n.encoding" value="utf-8"></constant>
 3    <constant name="struts.multipart.saveDir" value="f:\"></constant>
 4    <package name="struts2" extends="struts-default">
 5        <action name="upload" class="com.action.UpDownloadAction" method="uploadFiile">
 6            <result name="success">/jsp/result.jsp</result>
 7            <interceptor-ref name="fileUpload">
 8 <!--maximumSize (可選) - 這個攔截器允許的上傳到action中的文件最大長度(以byte為單位).
 9     注意這個參數和在webwork.properties中定義的屬性沒有關系,默認2MB-->
10                 <param name="maximumSize">409600</param>
11 <!--allowedTypes (可選) - 以逗號分割的contentType類型列表(例如text/html),
12 這些列表是這個攔截器允許的可以傳到action中的contentType.如果沒有指定就是允許任何上傳類型.-->
13                 <param name="allowedTypes">
14                     text/plain
15                 </param>
16             </interceptor-ref>
17             <interceptor-ref name="defaultStack"></interceptor-ref>
18        </action>
19        <action name="download" class="com.action.UpDownloadAction" method="downloadFile" >
20             <result name="success" type="stream">
21             <!--指定文件下載類型     application/octet-stream默認值可以下載所有類型    -->
22                 <param name="contentType">
23                     application/txt;
24                 </param>
25             <!-- 指定下載的文件名和顯示方式 ,但注意中文名的亂碼問題,解決辦法是:進行編碼處理-->
26             <!--contentDisposition是文件下載的處理方式,包括內聯(inline)和附件(attachment),
27             默認是inline, 使用附件時這樣配置:attachment;filename="文件名" 。-->
28                 <param name="contentDisposition">
29                   attachment;filename="${fileName}"
30                 </param>
31             <!--由getDownloadFile()方法獲得inputStream-->
32                 <param name="inputName">downloadFile</param>
33 <!--                指定下載文件的緩存大小-->
34                 <param name="bufferSize">2048</param>
35             </result>
36         </action>
37    </package>
38 </struts>  

一個簡單的Struts2的多文件文件上傳和單文件下載就實現了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM