struts2框架(三)文件上傳與下載

通過struts-default.xml里面的fileUpload攔截器實現(xiàn)文件上傳與下載豌注。
<interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>

1.FileUploadInterceptor里面的相關(guān)方法

 /**
     * Sets the allowed extensions
     * 限制運行的文件的擴展名
     * @param allowedExtensions A comma-delimited list of extensions
     */
    public void setAllowedExtensions(String allowedExtensions) {
        allowedExtensionsSet = TextParseUtil.commaDelimitedStringToSet(allowedExtensions);
    }

    /**
     * Sets the allowed mimetypes
     * 設(shè)置允許的mimetype
     * @param allowedTypes A comma-delimited list of types
     */
    public void setAllowedTypes(String allowedTypes) {
        allowedTypesSet = TextParseUtil.commaDelimitedStringToSet(allowedTypes);
    }

    /**
     * Sets the maximum size of an uploaded file
     * 設(shè)置上傳的最大文件大小
     * @param maximumSize The maximum size in bytes
     */
    public void setMaximumSize(Long maximumSize) {
        this.maximumSize = maximumSize;
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
     */

    public String intercept(ActionInvocation invocation) throws Exception {
        ActionContext ac = invocation.getInvocationContext();

        HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

        if (!(request instanceof MultiPartRequestWrapper)) {
            if (LOG.isDebugEnabled()) {
                ActionProxy proxy = invocation.getProxy();
                LOG.debug(getTextMessage("struts.messages.bypass.request", new Object[]{proxy.getNamespace(), proxy.getActionName()}, ac.getLocale()));
            }

            return invocation.invoke();
        }

        ValidationAware validation = null;

        Object action = invocation.getAction();

        if (action instanceof ValidationAware) {
            validation = (ValidationAware) action;
        }

        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;

        if (multiWrapper.hasErrors()) {
            for (String error : multiWrapper.getErrors()) {
                if (validation != null) {
                    validation.addActionError(error);
                }

                if (LOG.isWarnEnabled()) {
                    LOG.warn(error);
                }
            }
        }

        // bind allowed Files
        Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
        while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
            // get the value of this input tag
           // 獲取標(biāo)簽名file1
            String inputName = (String) fileParameterNames.nextElement();

            // get the content type
            String[] contentType = multiWrapper.getContentTypes(inputName);

            if (isNonEmpty(contentType)) {
                // get the name of the file from the input tag
                String[] fileName = multiWrapper.getFileNames(inputName);

                if (isNonEmpty(fileName)) {
                    // get a File object for the uploaded File
                    File[] files = multiWrapper.getFiles(inputName);
                    if (files != null && files.length > 0) {
                        List<File> acceptedFiles = new ArrayList<File>(files.length);
                        List<String> acceptedContentTypes = new ArrayList<String>(files.length);
                        List<String> acceptedFileNames = new ArrayList<String>(files.length);
                        String contentTypeName = inputName + "ContentType";
                        String fileNameName = inputName + "FileName";

                        for (int index = 0; index < files.length; index++) {
                            if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) {
                                acceptedFiles.add(files[index]);
                                acceptedContentTypes.add(contentType[index]);
                                acceptedFileNames.add(fileName[index]);
                            }
                        }

                        if (!acceptedFiles.isEmpty()) {
                            Map<String, Object> params = ac.getParameters();

                            params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));
                            params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));
                            params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));
                        }
                    }
                } else {
                    if (LOG.isWarnEnabled()) {
                    LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new Object[]{inputName}, ac.getLocale()));
                    }
                }
            } else {
                if (LOG.isWarnEnabled()) {
                    LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new Object[]{inputName}, ac.getLocale()));
                }
            }
        }

        // invoke action
        return invocation.invoke();
    }

2.文件上傳與下載實例

FileUpload:文件上傳Action

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUpload extends ActionSupport {

    // 對應(yīng)表單:<input type="file" name="file1">
    private File file1;
    // 文件名
    private String file1FileName;
    // 文件的類型(MIME)
    private String file1ContentType;

    public void setFile1(File file1) {
        this.file1 = file1;
    }

    public void setFile1FileName(String file1FileName) {
        this.file1FileName = file1FileName;
    }

    public void setFile1ContentType(String file1ContentType) {
        this.file1ContentType = file1ContentType;
    }

    @Override
    public String execute() throws Exception {
        /****** 拿到上傳的文件崖面,進(jìn)行處理 ******/
        // 把文件上傳到upload目錄

        // 獲取上傳的目錄路徑
        String path = ServletActionContext.getServletContext().getRealPath(
                "/upload");
        // 創(chuàng)建目標(biāo)文件對象
        File destFile = new File(path, file1FileName);
        // 把上傳的文件孝鹊,拷貝到目標(biāo)文件中
        FileUtils.copyFile(file1, destFile);

        return SUCCESS;
    }
}

DownAction:文件列表展示和下載Action

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownAction extends ActionSupport {
    
    
    /*************1. 顯示所有要下載文件的列表*********************/
    public String list() throws Exception {
        
        //得到upload目錄路徑
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        // 目錄對象
        File file  = new File(path);
        // 得到所有要下載的文件的文件名
        String[] fileNames =  file.list();
        // 保存
        ActionContext ac = ActionContext.getContext();
        // 得到代表request的map (第二種方式)
        Map<String,Object> request= (Map<String, Object>) ac.get("request");
        request.put("fileNames", fileNames);
        return "list";
    }
    
    
    /*************2. 文件下載*********************/
    
    // 1. 獲取要下載的文件的文件名
    private String fileName;
    public void setFileName(String fileName) {
        // 處理傳入的參數(shù)中問題(get提交)
        try {
            fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 把處理好的文件名隘马,賦值
        this.fileName = fileName;
    }
    
    //2. 下載提交的業(yè)務(wù)方法 (在struts.xml中配置返回stream)
    public String down() throws Exception {
        return "download";
    }
    
    // 3. 返回文件流的方法
    public InputStream getAttrInputStream(){
        return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName);
    }
    
    // 4. 下載顯示的文件名(瀏覽器顯示的文件名)
    public String getDownFileName() {
        // 需要進(jìn)行中文編碼
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }

    
}

配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <package name="upload_" extends="struts-default">
        <!-- 注意: action 的名稱不能用關(guān)鍵字"fileUpload" -->
        <action name="fileUploadAction" class="cn.itcast.e_fileupload.FileUpload">
        
            <!-- 限制運行上傳的文件的類型 -->
            <interceptor-ref name="defaultStack">
                
                <!-- 限制運行的文件的擴展名 -->
                <param name="fileUpload.allowedExtensions">txt,jpg,jar</param>
                
                <!-- 限制運行的類型   【與上面同時使用打月,取交集】
                <param name="fileUpload.allowedTypes">text/plain</param>
                -->
                
            </interceptor-ref>
            
            <result name="success">/e/success.jsp</result>
            
            <!-- 配置錯誤視圖 -->
            <result name="input">/e/error.jsp</result>
        </action>
        
        <action name="down_*" class="cn.itcast.e_fileupload.DownAction" method="{1}">
            <!-- 列表展示 -->
            <result name="list">/e/list.jsp</result>
            <!-- 下載操作 -->
            <result name="download" type="stream">
            
                <!-- 運行下載的文件的類型:指定為所有的二進(jìn)制文件類型 -->
               <param name="contentType">application/octet-stream</param>
               
               <!-- 對應(yīng)的是Action中屬性: 返回流的屬性【其實就是getAttrInputStream()】 -->
               <param name="inputName">attrInputStream</param>
               
               <!-- 下載頭肿仑,包括:瀏覽器顯示的文件名 -->
               <param name="contentDisposition">attachment;filename=${downFileName}</param>
             
                <!-- 緩沖區(qū)大小設(shè)置 -->
               <param name="bufferSize">1024</param>
            </result>
        </action>
    </package>  
</struts>

上傳頁面表單:

<form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data">
        用戶名:<input type="text" name="userName"><br/>
               <%--name的取名file1要和上傳Action里面的字段對應(yīng)--%>
        文件:<input type="file" name="file1"><br/>        
        <input type="submit" value="上傳">
</form>

文件列表和下載頁面:

<table border="1" align="center">
        <tr>
            <td>編號</td>
            <td>文件名</td>
            <td>操作</td>
        </tr>
        <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        <c:forEach var="fileName" items="${fileNames}" varStatus="vs">
            <tr>
                <td>${vs.count }</td>
                <td>${fileName }</td>
                <td>
                    <!-- 構(gòu)建一個url -->
                    <c:url var="url" value="down_down">
                        <c:param name="fileName" value="${fileName}"></c:param>
                    </c:url>                    
                    <a href="${url }">下載</a>
                </td>
            </tr>
        </c:forEach>
</table>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末坑律,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子伯襟,更是在濱河造成了極大的恐慌猿涨,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件姆怪,死亡現(xiàn)場離奇詭異叛赚,居然都是意外死亡,警方通過查閱死者的電腦和手機稽揭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門俺附,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人溪掀,你說我怎么就攤上這事事镣。” “怎么了揪胃?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵璃哟,是天一觀的道長氛琢。 經(jīng)常有香客問我,道長随闪,這世上最難降的妖魔是什么阳似? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮蕴掏,結(jié)果婚禮上障般,老公的妹妹穿的比我還像新娘。我一直安慰自己盛杰,他們只是感情好挽荡,可當(dāng)我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著即供,像睡著了一般定拟。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上逗嫡,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天青自,我揣著相機與錄音,去河邊找鬼驱证。 笑死延窜,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的抹锄。 我是一名探鬼主播逆瑞,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼伙单!你這毒婦竟也來了获高?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤吻育,失蹤者是張志新(化名)和其女友劉穎念秧,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體布疼,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡摊趾,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了游两。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片严就。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖器罐,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情渐行,我是刑警寧澤轰坊,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布铸董,位于F島的核電站,受9級特大地震影響肴沫,放射性物質(zhì)發(fā)生泄漏粟害。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一颤芬、第九天 我趴在偏房一處隱蔽的房頂上張望悲幅。 院中可真熱鬧,春花似錦站蝠、人聲如沸汰具。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽留荔。三九已至,卻和暖如春澜倦,著一層夾襖步出監(jiān)牢的瞬間聚蝶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工藻治, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留碘勉,地道東北人。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓桩卵,卻偏偏與公主長得像验靡,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子吸占,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容