Struts2第六篇【文件上傳和下載】

前言

在講解開山篇的時候就已經說了,Struts2框架封裝了文件上傳的功能……..本博文主要講解怎麼使用Struts框架來完成文件上傳和下載java

回顧之前的文件上傳

首先,咱們先來回顧一下之前,咱們在web中上傳文件是怎麼作的….http://blog.csdn.net/hon_3y/article/details/66975268web

可使用FileUpload或者SmartUpload組件來完成文件上傳的功能。可是呢,FileUpload組件使用起來是比較麻煩的…而SmartUPload解決中文的問題也很是麻煩瀏覽器

使用Struts進行文件上傳

從要導入的jar包咱們就能夠知道:Struts內部仍是使用fileUpload上傳組件….可是它極大的簡化地咱們的具體操做服務器

那咱們怎麼用它呢??看下面的圖markdown

這裏寫圖片描述

  • 在Action中使用在表單中定義的name,就能夠獲取表明的上傳文件的File對象
  • 在Action中使用在表單中定義的name+FileName,就獲得上傳文件的名字

JSP頁面

在註冊頁面上擁有兩個上傳文件控件app

<form action="${pageContext.request.contextPath}/register" method="post" enctype="multipart/form-data">
    <input type="file" name="photo"><br>
    <input type="file" name="photo1"><br>
    <input type="submit" value="註冊"><br>
</form>

Action

獲得相對應的File對象、上傳文件名稱、上傳文件的類型框架

package fileupload;

import java.io.File;

/** * Created by ozc on 2017/5/2. */
public class FileUploadAction {

    //上傳文件對應的File對象
    private File photo;
    private File photo1;

    //獲得上傳文件的名稱
    private String photoFileName;
    private String photo1FileName;

    //獲得上傳文件的類型
    private String photoContentType;
    private String photo1ContentType;

    //給出相對應的setter
    public void setPhoto(File photo) {
        this.photo = photo;
    }

    public void setPhoto1(File photo1) {
        this.photo1 = photo1;
    }

    public void setPhotoFileName(String photoFileName) {
        this.photoFileName = photoFileName;
    }

    public void setPhoto1FileName(String photo1FileName) {
        this.photo1FileName = photo1FileName;
    }

    public void setPhotoContentType(String photoContentType) {
        this.photoContentType = photoContentType;
    }

    public void setPhoto1ContentType(String photo1ContentType) {
        this.photo1ContentType = photo1ContentType;
    }


    public String register() {

        System.out.println(photo1FileName);
        System.out.println(photoFileName);


        return "success";
    }



}

成功獲得數據:jsp

這裏寫圖片描述

這裏寫圖片描述


Action業務代碼:

public String register() throws IOException {

        //獲得上傳的路徑
        String path = ServletActionContext.getServletContext().getRealPath("upload");
        System.out.println(path);

        //建立文件對象
        File destFile = new File(path,photoFileName);

        //調用工具類方法,將文件拷貝過去
        FileUtils.copyFile(photo, destFile);

        return "success";
    }
  • 效果:

這裏寫圖片描述


文件下載

咱們之前是經過設置request消息頭來實現文件下載的…..那麼在Struts又如何實現文件下載呢??工具

咱們請求服務器處理都是經過Action類來完成的,可是呢,Action類的業務方法都是返回字符串。所以,Struts在<result>節點中提供了類型爲stream的type值。經過stream來配置相對應的信息,從而實現下載post

列出全部能夠下載的文件

  • Action類的業務方法
public class downLoadAction {

    //列出全部能夠下載的文件
    public String list() {

        //獲得upload文件夾
        String path = ServletActionContext.getServletContext().getRealPath("/upload");

        //建立file對象
        File file = new File(path);

        //列出文件下全部的文件
        File[] files = file.listFiles();

        //將這些文件存到request域中
        HttpServletRequest request = ServletActionContext.getRequest();
        request.setAttribute("files", files);
        return "list";
    }
}
  • Struts配置文件
<action name="down_*" class="fileupload.downLoadAction" method="{1}">
            <result name="{1}">/list.jsp</result>
           <!-- <result name="{1}" type="stream">/index.jsp</result>-->
        </action>
  • JSP顯示頁面
<c:if test="${files==null}">

    對不起,沒有下載的頁面

</c:if>

<c:if test="${files!=null}">

    <table border="1px">
        <tr>
            <td>編號</td>
            <td>文件名稱</td>
            <td>操做</td>
        </tr>
        <c:forEach items="${files}" varStatus="file" var="fileName">
            <tr>

                <td>${file.count}</td>

                    <%--若是直接寫fileName,輸出的名字帶有路徑,使用EL方法庫來截取--%>
                <td>${fn:substringAfter(fileName, "upload\\")}</td>
                <td>

                        <%--使用url標籤來構建url,否則超連接帶有中文,會出現亂碼--%>
                    <c:url var="url" value="down_downLoad">
                        <c:param name="fileName">${fn:substringAfter(fileName, "upload\\")}</c:param>
                    </c:url>

                    <a href="${url}">下載</a>

                </td>
            </tr>
        </c:forEach>

    </table>
</c:if>
  • Action代碼:
/** * 訪問Action的業務方法僅僅返回的是字符串。所以Struts在result節點提供了stream類型的type, * 指定了stream就表明着我這是要下載的... * <p> * 既然要下載文件,那麼確定須要幾樣東西: * 一、文件名 * 二、表明文件的流 */
    public String downLoad() {

        return "downLoad";
    }

    //獲得要下載的文件名,Struts提供了自動封裝的功能
    private String fileName;


    //若是文件名是中文的,那麼須要手動轉換,由於超連接是get方法提交
    public void setFileName(String fileName) throws UnsupportedEncodingException {
        fileName = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
        this.fileName = fileName;
        System.out.println(fileName);
    }

    //獲得表明下載文件流,該方法由Struts調用
    public InputStream getAttrInputStream() {
        return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName);
    }

    //下載時,顯示的名稱【若是是中文,可能會亂碼,所以要URLencode】---->在Struts.xml文件中經過${}可獲取
    public String getDownFileName() throws UnsupportedEncodingException {

        fileName = URLEncoder.encode(fileName, "UTF-8");
        return fileName;
    }
  • Struts.xml
<action name="down_*" class="fileupload.downLoadAction" method="{1}">
            <result name="{1}">/list.jsp</result>
            <result name="downLoad" type="stream">

                <!--運行下載的類型,指定爲全部的二進制文件-->
                <param name="contentType">application/octet-stream</param>

                <!-- 對應的是Action中屬性: 返回流的屬性【其實就是getAttrInputStream()】 -->
                <param name="inputName">attrInputStream</param>

                <!-- 下載頭,包括:瀏覽器顯示的文件名 -->               <!--${}這裏不是EL表達式-->
                <param name="contentDisposition">attachment;filename=${downFileName}</param>

                <!-- 緩衝區大小設置 -->
                <param name="bufferSize">1024</param>

            </result>
        </action>

效果

這裏寫圖片描述

相關文章
相關標籤/搜索