struts2實現單個和多個文件的上傳

        struts2本身沒有提供解析上傳文件內容的功能,但是他使用第三方組件提供對文件上傳的支持。struts2的默認的文件上傳組件是apache的commons-fileupload組件,該組件性能優異而且支持任意大小的文件上傳。commons-fileupload組件從1.1版本開始依賴apache的另一個項目:commons-io,本次使用的是2.0版本。

         struts2提供了一個文件上傳攔截器:org.apache.struts2.interceptor.FileUploadInterceptor,他負責調用頂層的文件上傳組件解析文件內容,併爲action準備與上傳文件相關的屬性值。處理文件上傳請求的action必須提供特殊樣式命名的屬性,例如需要上傳的是image圖片,那麼action中就應該提供以下三個屬性:

  1. image:java.io.File類型,上傳文件的File對象;
  2. imageFileName:上傳文件的文件名;
  3. imageContentType:上傳文件的內容類型(MIME類型);

         這三個屬性的值會由FileUploadInterceptor攔截器準備。

        以下就以實例介紹利用該組件實現單個和多個文件的上傳和下載。

1、新建web工程Struts2_FileUpload

2、編輯上傳文件的Action類,在其類中定義三個變量,分別代表上傳文件的對象,上傳文件的名稱,上傳文件的MIME類型,並重寫execute()方法,把上傳文件保存在WEB-INF/UploadFiles文件夾下。FileUploadAction類代碼如下:

package com.struts2.actions;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 文件上傳Action類
 * @author 江南漁翁
 */
public class FileUploadAction extends ActionSupport {
    // 代表上傳文件的file對象
    private File file;

    // 上傳文件名
    private String fileFileName;

    // 上傳文件的MIME類型
    private String fileContentType;

    // 上傳文件的描述信息
    private String description;

    // 保存上傳文件的目錄,相對於Web應用程序的根路徑,在struts.xml文件中配置
    private String uploadDir;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUploadDir() {
        return uploadDir;
    }

    public void setUploadDir(String uploadDir) {
        this.uploadDir = uploadDir;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    @Override
    public String execute() throws Exception {
        String newFileName = null;
        // 得到當前時間自1990年1月1日0時0分0秒開始流逝的毫秒數,將這個毫秒數作爲上傳文件的新文件名
        long now = new Date().getTime();
        // 得到保存上傳文件的目錄的真實路徑
        String path = ServletActionContext.getServletContext().getRealPath(uploadDir);
        File dir = new File(path);
        // 如果這個目錄不存在,則創建它
        if (!dir.exists()) {
            dir.mkdir();
        }
        int index = fileFileName.lastIndexOf('.');
        // 判斷上傳文件名是否有擴展名,以時間截取爲新的文件名
        if (index != -1) {
            newFileName = now + fileFileName.substring(index);
        } else {
            newFileName = Long.toString(now);
        }

        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        // 讀取保存在臨時目錄下的上傳文件,寫入到新的文件中
        try {
            FileInputStream fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            FileOutputStream fos = new FileOutputStream(new File(dir, newFileName));
            bos = new BufferedOutputStream(fos);

            byte[] buf = new byte[4096];

            int len = -1;
            while ((len = bis.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
        } finally {
            try {
                if (null != bis) {
                    bis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            try {
                if (null != bos) {
                    bos.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return SUCCESS;
    }
}

3、在項目的src目錄下新建struts-config文件夾,在其內新建fileupload.xml文件,配置FileUploadAction類,代碼如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 指定攔截器的DTD信息 -->
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
   
<struts>
	<constant name="struts.multipart.maxSize" value="100000000"/>
	<package name="upload" namespace="/upload" extends="fileupload">
		<action name="upload" class="com.struts2.actions.FileUploadAction">
			<interceptor-ref name="fileUpload">
				<param name="maximumSize">10000</param>
				<param name="allowedTypes">
					image/gif,image/jpeg,image/png
				</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"/>
			<result name="input">/fileupload.jsp</result>
			<result name="success">/success.jsp</result>
			<param name="uploadDir">/WEB-INF/UploadFiles</param>
		</action>
	</package>
</struts>


4、把fileupload.xml文件引入到struts.xml文件中,代碼如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 指定攔截器的DTD信息 -->
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
   
<struts>
	<!-- 通過常量配置Struts2所使用的解碼集 -->
	<constant name="struts.i18n.encoding" value="gbk" />
	<constant name="struts.devMode" value="true" />
	<include file ="struts-config/fileupload.xml" />
	<package name="fileupload" namespace="/fileupload" extends="struts-default"/>
</struts>

 

5、在src下新建org.apache.struts2包,並在這個包下新建struts-messages.properties文件,修改上傳過濾失敗後的提示錯誤信息內容,代碼如下:

#改變文件類型不允許的提示信息
struts.messages.error.content.type.not.allowed=您上傳的文件類型只能是圖片文件!請重新選擇!
#改變上傳文件太大的提示信息
struts.messages.error.file.too.large=您要上傳的文件太大,請重新選擇!



6、在WebContent下新建頁面fileupload.jsp,代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@taglib prefix="s" uri="/struts-tags"%>

		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>

<head>
<title>文件上傳</title>
</head>

<body>
		<h1>上傳文件</h1>
		<hr />
		<!-- 使用紅色的前景色輸出錯誤信息 -->
		<div style="color:red">
			<s:fielderror/>
		</div>
		<s:form action="upload/upload.action" method="post" enctype="multipart/form-data">
					<s:file name="file" label="請選擇上傳的文件" />
					<s:textarea name="description" cols="50" rows="10" label="文件描述"></s:textarea>
					<s:submit value="  上   傳   " align="center" cssClass="button"/>
		</s:form>
</body>
</html>


7、在同一文件夾下新建success.jsp,用來提示上傳成功的信息,代碼如下:



 

      

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章