JavaEE中struts2實現檔案上傳下載功能執行個體解析_java

來源:互聯網
上載者:User

本文執行個體為大家分享了struts2實現檔案上傳下載的具體實現代碼,供大家參考,具體內容如下

一、檔案上傳

struts提交的檔案組件上傳,
前台:
1)、提交方式POST
2)、表單類型 multipart/form-data
3)、input type=file
後台:
Apache提供的FileUpload組件

核心類:
FileItemFactory FileItem的工廠
ServletFileUpload servlet 中的檔案上傳的核心類
FileItem 封裝了上傳的表單檔案項的資訊
總之 檔案上傳,處理起來比較麻煩

Struts的檔案上傳
檔案上傳攔截器協助我們晚場了檔案上傳的功能

<interceptor   name="fileUpload" class="org.apache.structs2.interceptor.FileUploadInterceptor"/> 

upload.xml

<struts> <package name="upload_" extends="struts-default">  <!-- 注意: action 的名稱不能用關鍵字"fileUpload" -->  <action name="fileUploadAction" class="cn.itcast.e_fileupload.FileUpload">   <!-- 限制運行上傳的檔案的類型 -->   <interceptor-ref name="defaultStack">    <!-- 限制啟動並執行檔案的副檔名 -->    <param name="fileUpload.allowedExtensions">txt,jpg,jar</param>    <!-- 限制啟動並執行類型 【與上面同時使用,取交集】    <param name="fileUpload.allowedTypes">text/plain</param>    -->   </interceptor-ref>   <result name="success">/e/success.jsp</result>   <!-- 配置錯誤視圖 -->   <result name="input">/e/error.jsp</result>  </action> </package> </struts>

upload.jsp

<body> <form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data">  使用者名稱:<input type="text" name="userName"><br/>  檔案:<input type="file" name="file1"><br/>  <input type="submit" value="上傳"> </form> </body>

error.jsp

 <body> error.jsp<br/> <!-- 查看struts架構在運行時期產生的所有錯誤資訊 --> <%@ taglib uri="/struts-tags" prefix="s" %> <s:fielderror></s:fielderror> </body>success.jsp<body> success.jsp </body>

核心代碼
FileUpload .class

public class FileUpload extends ActionSupport { // 對應表單:<input type="file" name="file1"> private File file1;  // 檔案名稱 private String file1FileName; // 檔案的類型(MIME) private String file1ContentType; public void setFile1(File file1) {  this.file1 = file1; } public void setFile1FileName(String file1FileName) {  this.file1FileName = file1FileName; } public void setFile1ContentType(String file1ContentType) {  this.file1ContentType = file1ContentType; } @Override public String execute() throws Exception {  /******拿到上傳的檔案,進行處理******/  // 把檔案上傳到upload目錄  // 擷取上傳的目錄路徑  String path = ServletActionContext.getServletContext().getRealPath("/upload");  // 建立目標檔案對象  File destFile = new File(path,file1FileName);  // 把上傳的檔案,拷貝到目標檔案中  FileUtils.copyFile(file1, destFile);  return SUCCESS; }}

檔案上傳處理細節

a.檔案大小限制
structs預設支援的檔案上傳最大是2M,通過常量修改:

    <!-- 4. 修改上傳檔案的最大大小為30M -->
    <constant name="struts.multipart.maxSize" value="31457280"/>

b.限制上傳檔案的允許類型
需求:只允許txt/jpg尾碼的檔案
攔截器:注入參數從而限制檔案上傳類型

 <!-- 限制運行上傳的檔案的類型 -->   <interceptor-ref name="defaultStack">    <!-- 限制啟動並執行檔案的副檔名 -->    <param name="fileUpload.allowedExtensions">txt,jpg,jar</param>    <!-- 限制啟動並執行類型 【與上面同時使用,取交集】    <param name="fileUpload.allowedTypes">text/plain</param>    -->   </interceptor-ref>

、檔案的下載

struts檔案下載,2種方式:
方式1:通過response對象向瀏覽器寫入位元組流資料;設定下載的回應標頭
方式2:struts的方式

struts的檔案下載:

複製代碼 代碼如下:
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>

首先注意在webroot目錄下建立 upload 檔案夾,把你要提供下載的檔案放到該檔案夾下,

upload.xml

<action name="down_*" class="cn.itcast.e_fileupload.DownAction" method="{1}">   <!-- 列表展示 -->   <result name="list">/e/list.jsp</result>   <!-- 下載操作 -->   <result name="download" type="stream">    <!-- 運行下載的檔案的類型:指定為所有的二進位檔案類型 -->    <param name="contentType">application/octet-stream</param>    <!-- 對應的是Action中屬性: 返迴流的屬性【其實就是getAttrInputStream()】 -->    <param name="inputName">attrInputStream</param>    <!-- 下載頭,包括:瀏覽器顯示的檔案名稱 -->    <param name="contentDisposition">attachment;filename=${downFileName}</param>    <!-- 緩衝區大小設定 -->    <param name="bufferSize">1024</param>   </result>  </action>

list.jsp

<body> <table border="1" align="center">  <tr>   <td>編號</td>   <td>檔案名稱</td>   <td>操作</td>  </tr>  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  <c:forEach var="fileName" items="${fileNames}" varStatus="vs">   <tr>    <td>${vs.count }</td>    <td>${fileName }</td>    <td>     <!-- 構建一個url -->     <c:url var="url" value="down_down">      <c:param name="fileName" value="${fileName}"></c:param>     </c:url>     <a href="${url }">下載</a>    </td>   </tr>  </c:forEach> </table> </body>

DownAction

/** * 檔案下載 * 1. 顯示所有要下載檔案的列表 * 2. 檔案下載 * */public class DownAction extends ActionSupport { /*************1. 顯示所有要下載檔案的列表*********************/ public String list() throws Exception {  //得到upload目錄路徑  String path = ServletActionContext.getServletContext().getRealPath("/upload");  // 目錄對象  File file = new File(path);  // 得到所有要下載的檔案的檔案名稱  String[] fileNames = file.list();  // 儲存  ActionContext ac = ActionContext.getContext();  // 得到代表request的map (第二種方式)  Map<String,Object> request= (Map<String, Object>) ac.get("request");  request.put("fileNames", fileNames);  return "list"; } /*************2. 檔案下載*********************/ // 1. 擷取要下載的檔案的檔案名稱 private String fileName; public void setFileName(String fileName) {  // 處理傳入的參數中問題(get提交)  try {   fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");  } catch (UnsupportedEncodingException e) {   throw new RuntimeException(e);  }  // 把處理好的檔案名稱,賦值  this.fileName = fileName; } //2. 下載提交的業務方法 (在struts.xml中配置返回stream) public String down() throws Exception {  return "download"; } // 3. 返迴文件流的方法 public InputStream getAttrInputStream(){  return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName); } // 4. 下載顯示的檔案名稱(瀏覽器顯示的檔案名稱) public String getDownFileName() {  // 需要進行中文編碼  try {   fileName = URLEncoder.encode(fileName, "UTF-8");  } catch (UnsupportedEncodingException e) {   throw new RuntimeException(e);  }  return fileName; }}

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.