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>

效果

这里写图片描述

相关文章
相关标签/搜索