java中struts2實現檔案上傳下載功能_java

來源:互聯網
上載者:User

先談一談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頁面

<body><s:form> <div style="border:1px solid black">成功上傳的檔案:<br>  <ul style="list-style-type:decimal"> <s:iterator value="#request.fileName" id="file" status="status">   <li><s:property/> </li> </s:iterator>  </ul> </div></s:form></body>

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

二、建立updown.js檔案,在index.jsp中引用

function checkf(){ var files = document.getElementsByName("file"); if(files[0].value.length!=0){   return true;  }else{  alert("請選擇檔案");  return false;  }}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);}

三、建立upDownloadAction.java

package com.action;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.util.List;import javax.servlet.http.HttpServletRequest;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.ServletActionContext;public class UpDownloadAction extends ActionSupport { private static final long serialVersionUID = 1L; private List<File> file;// 對應jsp中file標籤 private List<String> fileFileName;//  private List<String> fileContentType;//  private String fileName;//獲得jsp中pram參數 @SuppressWarnings("deprecation") // 檔案上傳 public String uploadFiile() throws Exception {  String root = ServletActionContext.getServletContext().getRealPath(    "/upload");// 上傳路徑  System.out.println(root);  InputStream inputStream;  File destFile;  OutputStream os;  for (int i = 0; i < file.size(); i++) {   inputStream = new FileInputStream(file.get(i));   destFile = new File(root, this.getFileFileName().get(i));   os = new FileOutputStream(destFile);   byte[] buffer = new byte[400];   int length = 0;   while ((length = inputStream.read(buffer)) > 0) {    os.write(buffer, 0, length);   }   inputStream.close();   os.close();  }  HttpServletRequest request = ServletActionContext.getRequest();  request.setAttribute("fileName", fileFileName);  return SUCCESS; } // 檔案下載 public InputStream getDownloadFile() throws FileNotFoundException,   UnsupportedEncodingException {  System.out.println(getFileName());  // 如果下載檔案名稱為中文,進行字元編碼轉換  ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="      + java.net.URLEncoder.encode(fileName, "UTF-8"));  InputStream inputStream = new FileInputStream("F:/" //使用絕對路徑 ,從該路徑下載“測試.txt"檔案    + this.getFileName());  System.out.println(inputStream);  return inputStream; } // 下載 public String downloadFile() throws Exception {  return SUCCESS; } public String getFileName() throws UnsupportedEncodingException {  return fileName; } public void setFileName(String fileName)   throws UnsupportedEncodingException {  this.fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8"); } }

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

四、最後是設定檔

1、web.xml配置

<filter>   <filter-name>struts2</filter-name>   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  </filter>    <filter-mapping>   <filter-name>struts2</filter-name>   <url-pattern>/*</url-pattern>  </filter-mapping>

2、struts.xml配置

<struts>  <constant name="struts.i18n.encoding" value="utf-8"></constant> <constant name="struts.multipart.saveDir" value="f:\"></constant> <package name="struts2" extends="struts-default">  <action name="upload" class="com.action.UpDownloadAction" method="uploadFiile">   <result name="success">/jsp/result.jsp</result>   <interceptor-ref name="fileUpload"><!--maximumSize (可選) - 這個攔截器允許的上傳到action中的檔案最大長度(以byte為單位). 注意這個參數和在webwork.properties中定義的屬性沒有關係,預設2MB-->    <param name="maximumSize">409600</param><!--allowedTypes (可選) - 以逗號分割的contentType類型列表(例如text/html),這些列表是這個攔截器允許的可以傳到action中的contentType.如果沒有指定就是允許任何上傳類型.-->    <param name="allowedTypes">     text/plain    </param>   </interceptor-ref>   <interceptor-ref name="defaultStack"></interceptor-ref>  </action>  <action name="download" class="com.action.UpDownloadAction" method="downloadFile" >   <result name="success" type="stream">   <!--指定檔案下載類型  application/octet-stream預設值可以下載所有類型 -->    <param name="contentType">     application/txt;    </param>   <!-- 指定下載的檔案名稱和顯示方式 ,但注意中文名的亂碼問題,解決辦法是:進行編碼處理-->   <!--contentDisposition是檔案下載的處理方式,包括內聯(inline)和附件(attachment),   預設是inline, 使用附件時這樣配置:attachment;filename="檔案名稱" 。-->    <param name="contentDisposition">     attachment;filename="${fileName}"    </param>   <!--由getDownloadFile()方法獲得inputStream-->    <param name="inputName">downloadFile</param><!--    指定下載檔案的緩衝大小-->    <param name="bufferSize">2048</param>   </result>  </action> </package></struts>

一個簡單的Struts2多檔案上傳單檔案下載就實現了。

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.