菜鳥學SSH(五)——Struts2上傳檔案

劉水鏡發表於2013-12-11

上傳檔案在一個系統當中是一個很常用的功能,也是一個比較重要的功能。今天我們就一起來學習一下Struts2如何上傳檔案。

今天講的上傳檔案的方式有三種:

1,以位元組為單位傳輸檔案;

2,Struts2封裝的一種方式;

3,以字元的方式傳輸檔案。


其實這三種方式都差不多,都是將檔案先從客戶端一臨時檔案的形式,傳輸到伺服器的臨時資料夾下,然後在將該臨時檔案複製到我們要上傳的目錄。另外,有一個需要注意,就是上傳過程中產生的這些臨時檔案,Struts2不會自動清理,所以我們需要手動清理臨時檔案,這一個下面的程式碼中有提到。


用Action來完成我們上傳的核心功能:

package com.action;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


public class UploadAction extends ActionSupport {

    private File upload;
    private String uploadFileName;    
    private String uploadContentType;
    
    private long maximumSize;
    private String allowedTypes;
    

    public File getUpload() {
        return upload;
    }
    public void setUpload(File upload) {
        this.upload = upload;
    }
    public String getUploadFileName() {
        return uploadFileName;
    }
    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }
    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }
    public long getMaximumSize() {
        return maximumSize;
    }
    public void setMaximumSize(long maximumSize) {
        this.maximumSize = maximumSize;
    }
    public String getAllowedTypes() {
        return allowedTypes;
    }
    public void setAllowedTypes(String allowedTypes) {
        this.allowedTypes = allowedTypes;
    }
    @Override
    public String execute() throws Exception {
        
        File uploadFile = new File(ServletActionContext.getServletContext().getRealPath("upload"));
        if(!uploadFile.exists()) {
            uploadFile.mkdir();
        }
        
        //驗證檔案大小及格式
        if (maximumSize < upload.length()) {
            return "error";
        }
        
        boolean flag =false;
        String[]  allowedTypesStr = allowedTypes.split(",");
        for (int i = 0; i < allowedTypesStr.length; i++) {
            if (uploadContentType.equals(allowedTypesStr[i])) {
                flag = true;
            }
        }
        if (flag == false) {
            Map request = (Map) ActionContext.getContext().get("request");
            request.put("errorMassage", "檔案型別不合法!");
            
            System.out.println(request.toString());
            return "error";
        }
        
        //第一種上傳方式
//        FileInputStream input = new FileInputStream(upload);
//        FileOutputStream out = new FileOutputStream(uploadFile +"//"+ uploadFileName);
//        try {
//            byte[] b =new byte[1024];
//            int i = 0;
//            while ((i=input.read(b))>0) {
//                out.write(b, 0, i);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            //關閉輸入、輸出流
//            input.close();
//            out.close();
//            //刪除臨時檔案
//            upload.delete();
//        }
        
        //第二種上傳方式
//        FileUtils.copyFile(upload, new File(uploadFile+"\\"+uploadFileName));
//        //刪除臨時檔案
//        upload.delete();
        
        //第三種上傳方式
        BufferedReader bReader = new BufferedReader(new InputStreamReader(new FileInputStream(upload)));
        BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(uploadFile+"\\"+ uploadFileName)));
        try {
            char [] c =new char[1024];
            int i = 0;
            while ((i = bReader.read(c)) > 0) {
                bWriter.write(c, 0, i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bReader.close();
            bWriter.close();            
            //刪除臨時檔案
            upload.delete();
        }
        
        
        return "success";
    }    
    
}

 



在Struts.xml檔案中配置我們的Action:

 

<?xml version="1.0" encoding="UTF-8" ?>  
<!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.action.extension" value=","></constant>  
    <!-- 上傳檔案最大限制(如果為多檔案上傳,則為多個檔案的總大小) -->  
    <constant name="struts.multipart.maxSize" value="40000000"></constant>  
    <!-- 存放上傳檔案的臨時目錄 -->  
    <constant name="struts.multipart.saveDir" value="D:\\temp"></constant>    
      
      
    <package name="upload" namespace="/file" extends="struts-default">  
        <action name="upLoad" class="com.action.UploadAction">  
            <result name="success">/success.jsp</result>  
            <result name="error" >/error.jsp</result>  
            <result name = "input" type ="redirect">/index.jsp</result>  
            <param name="maximumSize ">1000000</param>  
            <param name="allowedTypes">application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain</param>  
  
            <!--用struts攔截器限制上傳檔案大小及型別  
            <interceptor-ref name="fileUpload">  
                單個檔案的大小  
                <param name="maximumSize ">1000000</param>  
                <param name="allowedTypes">application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain</param>  
            </interceptor-ref>  
            <interceptor-ref name="defaultStack"></interceptor-ref>  
             -->  
        </action>  
          
    </package>  
  
</struts>  

 

 

 

 



檔案上傳的頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上傳檔案</title>
</head>
<body>
    <!-- enctype="multipart/form-data"不對字元編碼。在使用包含檔案上傳控制元件的表單時,必須使用該值。 -->
    <form action="file/upLoad" method="post" enctype="multipart/form-data">
        <input name="upload" type="file">
        <input name="btnUpload" type="submit" value="上傳">
    </form>
</body>
</html>

 


上傳檔案之前,通常要判斷一下檔案的大小及型別,上面有兩種方式來驗證,一種是在Action裡驗證,一種是通過Struts2的攔截器驗證。兩者選其一,選擇一個把另一個註釋掉即可。


另外,還有一個需要注意:上傳檔案頁面中form的enctype屬性值,一定要設定成"multipart/form-data",否則就會出錯。


OK,今天上傳檔案就向大家介紹到這裡,我們下篇部落格再見!





相關文章