Struts2學習總結——文件上傳與下載

Struts2文件上傳與下載

1.1.1新建一個Maven項目(demo02)css

在此添加Web構面以及 struts2 構面html

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

<?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)jquery

<?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>web\WEB-INF\web.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包以下:web

1.3.1編寫上傳文件頁面(upload.jsp)ajax

<%@ 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>

 

運行效果:apache

1.4.1struts.xml文件json

<?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.propertiesapi

    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實例下載

相關文章
相關標籤/搜索