Struts2檔案上傳和檔案下載,struts2檔案上傳

來源:互聯網
上載者:User

Struts2檔案上傳和檔案下載,struts2檔案上傳

一、前言

  由於Struts2架構對上傳組件進行了封裝,使得檔案上傳的實現簡單。

  在Struts2架構中提供對commons-fileupload組件的支援,並且預設使用該組件實現檔案上傳。因此,為了實現檔案上傳功能,我們需要在項目中包含如下兩個jar檔案:

  commons-fileupload-x.x.x.jar、commons-io-x.x.x.jar  注意:jar檔案版本取決於當前工程使用的Struts2的版本。

二、實現檔案上傳

1)上傳頁面的準備

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@taglib uri="/struts-tags" prefix="s"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>檔案上傳</title>  </head>    <body>          <s:form action="upload" enctype="multipart/form-data" method="post">              <s:textfield name="title" label="標題"/>              <s:file name="upload" label="選擇檔案"/>              <s:submit name="submit" value="檔案上傳"/>                    </s:form>  </body></html>

2)開發實現檔案上傳的Action

package cn.happy.action;import java.io.FileInputStream;import java.io.FileOutputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class UploadAction extends ActionSupport implements Action{        //封裝上傳檔案屬性        private String upload;        //封裝上傳檔案的類型        private String uploadContentType;        //封裝上傳檔案的名稱        private String uploadFileName;        //擷取檔案上傳路徑        private String savePath;                @Override        public String execute() throws Exception{            byte[] buffer=new byte[1024];            //讀取檔案            FileInputStream fis=new FileInputStream(getUpload());            //儲存檔案,並設定儲存目錄的路徑            FileOutputStream fos=new FileOutputStream(getSavePath()+"\\"+this.getUploadFileName());            int length=fis.read(buffer);            while(length>0){                //每次寫入長度的內容                fos.write(buffer,0,length);                length=fis.read(buffer);            }            fis.close();            fos.flush();            fos.close();            return SUCCESS;                    }        //擷取上傳檔案的儲存路徑        //通過讀取存放目錄擷取的儲存路徑        public String getSavePath() {            return ServletActionContext.getServletContext().getRealPath(savePath);        }        public void setSavePath(String savePath) {            this.savePath = savePath;        }        public String getUpload() {            return upload;        }        public void setUpload(String upload) {            this.upload = upload;        }        public String getUploadContentType() {            return uploadContentType;        }        public void setUploadContentType(String uploadContentType) {            this.uploadContentType = uploadContentType;        }        public String getUploadFileName() {            return uploadFileName;        }        public void setUploadFileName(String uploadFileName) {            this.uploadFileName = uploadFileName;        }                                }

3)Struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"><struts >    <!--  <constant name="struts.devMode" value="true" /> -->     <constant name="struts.devMode" value="false" />      <!--建立一個default包,繼承自Struts2的struts-default包  -->    <package name="default" namespace="" extends="struts-default">    <action name="upload" class="cn.happy.action.UploadAction">        <!-- 通過param參數設定儲存目錄路徑 -->        <param name="savePath">/upload</param>        <result name="success">upload_success.jsp</result>        </action></package>  </struts>

4)在成功頁面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@taglib uri="/struts-tags" prefix="s"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>檔案上傳成功</title>          </head>    <body>  您所上傳的檔案是:<s:property value="uploadFileName"/> 檔案類型:<s:property value="uploadContentType"/> 檔案路徑:<s:property value="savePath"/>  </body></html>

三、實現檔案下載

1)下載頁面準備

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@taglib uri="/struts-tags" prefix="s"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>檔案下載</title>  </head>    <body>    <a href="download?fileName=007.jpg">點擊此處下載文檔</a>  </body></html>

2)開始實現檔案下載的Action

package cn.happy.action;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class FileDownAction  extends ActionSupport {        //讀取下載的檔案目錄    private String inputPath;    //下載檔案的檔案名稱    private String fileName;    //讀取下載檔案的輸入資料流       @SuppressWarnings("unused")    private InputStream inputStream;        //下載的檔案類型    private String conetntType;    //建立inputStream輸入資料流        @Override    public String execute() throws Exception {                return SUCCESS;    }            public InputStream getInputStream() throws FileNotFoundException {        String path=ServletActionContext.getServletContext().getRealPath(inputPath);        return new BufferedInputStream(new FileInputStream(path+"\\"+fileName));    }    public void setInputStream(InputStream inputStream) {        this.inputStream = inputStream;    }    public String getInputPath() {        return inputPath;    }    public void setInputPath(String inputPath) {        this.inputPath = inputPath;    }    public String getFileName() {        return fileName;    }    public void setFileName(String fileName) {        this.fileName = fileName;    }    public String getConetntType() {        return conetntType;    }    public void setConetntType(String conetntType) {        this.conetntType = conetntType;    }        }

3)Struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"><struts >    <!--  <constant name="struts.devMode" value="true" /> -->     <constant name="struts.devMode" value="false" />      <!--建立一個default包,繼承自Struts2的struts-default包  -->    <package name="default" namespace="" extends="struts-default">    <action name="upload" class="cn.happy.action.UploadAction">              <!-- 檔案下載 -->        <action name="download" class="cn.happy.action.FileDownAction">            <param name="inputPath">/upload</param>            <result name="success" type="stream">                <param name="conetntType">application/octet-stream</param>                <!-- <param name="conetntType">image/gif</param> -->                <param name="inputName">inputStream</param>                <param name="contentDisposition">attachement;filename="${fileName}"</param>                <param name="bufferSize">4096</param>            </result>        </action>            </package>                </struts>

注意!!!!

                        contentType對應的檔案類型

        檔案類型                                                           contentType設定                                        
  Word     application/msword
  Execl     Application/vnd.ms-excel
  PPT     Application/vnd.ms-powerpoint
  圖片     image/gif、image/bmp、image/jpeg
  文字檔     text/plain
  HTML網頁     text/html
  可執行檔     application/octet-stream

聯繫我們

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