• Struts2学习总结——文件上传与下载


    Struts2文件上传与下载

    1.1.1新建一个Maven项目(demo02)

    在此添加Web构面以及 struts2 构面

    1.2.1配置Maven依赖(pom.xml 文件)

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.nf</groupId>
            <artifactId>parent</artifactId>
            <version>1.0-SNAPSHOT</version>
            <relativePath>../pom.xml</relativePath>
        </parent>
        <artifactId>demo02</artifactId>
        <packaging>war</packaging>
        <version>1.0-SNAPSHOT</version>
    </project> 

    1.2.2 项目中pom文件所继承的父文件(pom.xml)

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>parent</artifactId>
        <groupId>org.nf</groupId>
        <version>1.0-SNAPSHOT</version>
        <packaging>pom</packaging>
        <properties>
            <!-- 设置整个maven项目的编码格式 -->
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <!-- 设置控制台输出参数的编码格式, 解决乱码  -->
            <orgLine>-Dfile.encoding=UTF-8</orgLine>
        </properties>
    
        <build>
            <plugins>
                <!-- 配置maven编译插件,指定maven编译版本 -->
                <plugin>
                    <!-- 插件名称 -->
                    <artifactId>maven-compiler-plugin</artifactId>
                    <!-- 插件配置信息 -->
                    <configuration>
                        <target>1.8</target>
                        <source>1.8</source>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
    
                <plugin>
                    <!-- 插件名称 -->
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <warSourceDirectory>web</warSourceDirectory>
                        <webXml>webWEB-INFweb.xml</webXml>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    
        <!-- 添加Struts依赖 -->
        <dependencies>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-core</artifactId>
                <version>2.5.8</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-json-plugin</artifactId>
                <version>2.5.8</version>
            </dependency>
        </dependencies>
    </project>

    1.2.3所添加好的依赖jar包如下:

    1.3.1编写上传文件页面(upload.jsp)

    <%@ taglib prefix="s" uri="/struts-tags" %>
    <%--
      Created by IntelliJ IDEA.
      User: YongLin
      Date: 2017/2/9
      Time: 下午2:44
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Upload</title>
    </head>
    <body>
    
       <!--方式一: 使用struts错误信息提示的标签,会自动输出错误信息 -->
       <s:fielderror cssStyle="color: red"/>
    
       <!--方式二: 使用el表达式来获取错误信息,uploadFile对应input的name,它是一个数组
       当多文件上传时,应该循环遍历这个数组来显示提示信息的内容-->
       <%--<font color="red">${fieldErrors.uploadFile[0]}</font>--%>
       <form method="post" action="upload" enctype="multipart/form-data">
            File:<input type="file" name="uploadFile"/><br/>
            Readme:<input type="text" name="readme"/><br/>
           <input type="submit" value="submit"/>
       </form>
    </body>
    </html>

    运行效果:

    1.4.1struts.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    
    <!DOCTYPE struts PUBLIC
            "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
            "http://struts.apache.org/dtds/struts-2.5.dtd">
    
    <struts>
        <!-- 设置编码格式,防止上传的文件名为中文时是乱码 -->
        <constant name="struts.i18n.encoding" value="UTF-8"/>
        <!-- 指定resource资源文件的名称-->
        <constant name="struts.custom.i18n.resources" value="message"/>
        <!-- 设置上传文件的总大小(单位:字节),默认是10M -->
        <constant name="struts.multipart.maxSize" value="104857600"/>
    
        <package name="struts" extends="struts-default,json-default">
            <!-- 配置上传的拦截器 -->
            <interceptors>
                <interceptor-stack name="myStack">
                    <!-- 配置上传的拦截器 -->
                    <interceptor-ref name="fileUpload">
                        <!-- 限制上传的文件类型,这里限制为只能上传各种图片类型 -->
                        <!--<param name="allowedTypes">image/bmp,image/png,image/jpg,image/jpeg</param>-->
                        <!-- 限制上传文件的大小(单位是字节)-->
                        <!--<param name="maximumSize">2097152</param>-->
                    </interceptor-ref>
                    <!-- 引用默认的拦截器栈 -->
                    <interceptor-ref name="defaultStack"/>
                </interceptor-stack>
            </interceptors>
    
            <!-- 普通上传 -->
            <action name="upload" class="org.demo02.action.DemoAction" method="upload">
                <!-- 引用拦截器 -->
                <interceptor-ref name="myStack"/>
                <!-- 上传成功后跳转的页面 -->
                <result>index.jsp</result>
    
                <!-- 上传失败或有错误的提示页面,
                name="input"表示当有错误信息的时候要跳转到的提示页面-->
                <result name="input">upload.jsp</result>
            </action>
    
            <!-- ajax上传,后台的上传方法是一样的,不同的是result的配置 -->
            <action name="ajaxUpload" class="org.demo02.action.DemoAction" method="upload">
                <!-- 引用拦截器 -->
                <interceptor-ref name="myStack"/>
                <result type="json">
                    <param name="root">message</param>
                </result>
                <!-- 使用json结果集类型返回错误信息,用于ajax请求
                 struts会将fieldErrors序列化成json对象 -->
                <result name="input" type="json">
                    <param name="root">fieldErrors</param>
                </result>
            </action>
    
            <!-- 文件下载 -->
            <action name="download" class="org.demo02.action.DownloadAction" method="download">
                <!-- 文件下载的结果集类型使用stream,表示一个流 -->
                <result type="stream">
                    <!-- 设置一些下载的参数配置 -->
                    <!-- contentType表示设置response的响应类型,这里设置为流类型 -->
                    <param name="contentType">application/octet-stream</param>
                    <!-- contentDisposition指定响应回客户端的下载的文件名,
                    ${fileName}引用action中定义的fileName属性-->
                    <param name="contentDisposition">attachment;filename="${fileName}"</param>
                    <!-- inputName指定action中定义的getXxx方法,去掉get并将首字母改成小写 -->
                    <param name="inputName">inputStream</param>
                    <!-- 下载文件的缓冲大小(可选) -->
                    <param name="bufferSize">4096</param>
                </result>
            </action>
        </package>
    </struts>

    1.4.2 显示错误信息中文提示的:message.properties

        struts.messages.error.content.type.not.allowed = 不是允许的上传类型
        struts.messages.error.file.too.large = 已超出文件的限制大小

     1.4.3文件上传的action:DemoAction

    package org.demo02.action;
    
    import com.opensymphony.xwork2.ActionSupport;
    import org.apache.commons.io.FileUtils;
    import org.apache.struts2.ServletActionContext;
    
    import java.io.File;
    import java.io.IOException;
    
    /**
     * Created by YongLin on 17/2/9.
     */
    public class DemoAction extends ActionSupport {
        //表单文本数据
        private String readme;
    
        //表单文件,必须是一个File类型
        private File uploadFile;
        //上传的文件名,格式必须是File名称 + FileName
        private String uploadFileFileName;
        //上传的文件类型,格式必须是File名称 + ContentType
        private String uploadFileContentType;
    
        private String message;
    
        public String getReadme() {
            return readme;
        }
    
        public void setReadme(String readme) {
            this.readme = readme;
        }
    
        public File getUploadFile() {
            return uploadFile;
        }
    
        public void setUploadFile(File uploadFile) {
            this.uploadFile = uploadFile;
        }
    
        public String getUploadFileFileName() {
            return uploadFileFileName;
        }
    
        public void setUploadFileFileName(String uploadFileFileName) {
            this.uploadFileFileName = uploadFileFileName;
        }
    
        public String getUploadFileContentType() {
            return uploadFileContentType;
        }
    
        public void setUploadFileContentType(String uploadFileContentType) {
            this.uploadFileContentType = uploadFileContentType;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        //上传
        public String upload() throws IOException {
            //获取上传的绝对路径
            String uploadPath = ServletActionContext.getServletContext().getRealPath("/files");
            //如果提交过来的File不为null,才执行上传操作
            if(uploadFile != null){
                System.out.println(uploadFileFileName);
                System.out.println(uploadFileContentType);
                //根据文件名以及上传的路径构建一个新的File对象
                File saveFile = new File(uploadPath, uploadFileFileName);
                //先判断上传的目录是否存在,如果不存在则创建出来
                if(!saveFile.getParentFile().exists()){
                    saveFile.getParentFile().mkdirs();
                }
                //使用文件复制执行上传
                FileUtils.copyFile(uploadFile, saveFile);
                //提示成功信息
                message = "上传成功";
            }
            return "success";
        }
    }

     1.4.4 文件下载的action:DownloadAction

    package org.demo02.action;
    
    import com.opensymphony.xwork2.ActionSupport;
    import org.apache.struts2.ServletActionContext;
    
    import java.io.*;
    
    /**
     * Created by YongLin on 17/2/10.
     */
    public class DownloadAction extends ActionSupport {
    
        //要下载的文件名
        private String fileName;
    
        public String getFileName() {
            //解决下载文件时中文名时出现乱码
            try {
                fileName = new String(fileName.getBytes("utf-8"),
                        "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return fileName;
        }
    
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
    
        //我们需要提供一个方法,这个方法是一个标准的get方法,如getXxx
        //并通过这个方法创建并返回一个InputStream给struts
        //struts就会根据这个输入流读取文件,并写回客户端
        public InputStream getInputStream() throws Exception {
            //获取文件上传的目录
            String uploadPath = ServletActionContext.getServletContext().getRealPath("/files");
            //根据路径结合提交过来的文件名,创建一个File对象
            File file = new File(uploadPath, fileName);
            //创建InputStream对象
            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            //返回这个输入流给struts
            return inputStream;
        }
    
        public String download(){
            return "success";
        }
    
    }
    1.4.5Web.xml文件
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
        <filter> 
            <filter-name>dispatcher</filter-name>
            <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>dispatcher</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    </web-app>

     1.5.1index.jsp页面

    <%--
      Created by IntelliJ IDEA.
      User: YongLin
      Date: 2017/2/9
      Time: 下午2:44
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <html>
    <head>
        <title>Index</title>
    </head>
    <body>
      <!-- 显示文件名,并可以执行下载操作 -->
      <a href="download?fileName=<s:property value='uploadFileFileName'/>"><s:property value="uploadFileFileName"/></a>
    </body>
    </html>

     1.5.2Ajax 文件上传(需要引入jQery包)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="js/jquery-1.9.1.min.js"></script>
        <script>
            $(function(){
                $("#btn").on("click",function(){
                    //使用FormData来实现表单的封装和ajax上传
                    var formData = new FormData(document.getElementById("f1"));
                    //使用jquery的ajax提交表单
                    $.ajax({
                        url : "ajaxUpload", //请求的url
                        type : "post", //请求类型
                        data : formData, //表单数据
                        processData : false, //让Jquery不处理发送的数据
                        contentType : false,  //让Jquery不设置Content-Type请求头
                        success : function(result){ // 成功响应后的回调函数
                            if(result.uploadFile != undefined){
                                $("#msg").append("<font color='red'>"+result.uploadFile+"</font>");
                            }else{
                                $("#msg").append("<font color='red'>"+result+"</font>");
                            }
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
    <div id="msg"></div>
    <form id="f1" method="post" action="upload" enctype="multipart/form-data">
        File:<input type="file" name="uploadFile"/><br/>
        Readme:<input type="text" name="readme"/><br/>
        <input id="btn" type="button" value="button"/>
    </form>
    </body>
    </html>

     1.6.1运行效果:

    1.

    点击提交  文件上传成功过后来到index.jsp页面

    在页面中显示出文件名

    2.

    3.

      4.Ajax文件上传

    1.7.1Demo整体架构

    1.8实例下载

  • 相关阅读:
    读书笔记_Effective_C++_条款二:尽量以const, enum, inline替换#define
    读书笔记_代码大全_第14章_组织直线型代码_第15章_使用条件语句
    读书笔记_代码大全_第31章_布局与风格
    读书笔记_代码大全_第16章_控制循环
    读书笔记_Effective_C++_条款五:了解C++默默编写并调用哪些函数
    python学习笔记(三)——字符串
    python学习笔记(六)——函数
    Windows下安装Django
    python小专题——time模块
    python学习笔记(四)——数据字典
  • 原文地址:https://www.cnblogs.com/zhangyongl/p/6386893.html
Copyright © 2020-2023  润新知