SSH Struts2上傳文件

2018-09-28 18:55 更新

Struts2 上傳文件

上傳文件在一個(gè)系統(tǒng)當(dāng)中是一個(gè)很常用的功能,也是一個(gè)比較重要的功能。今天我們就一起來(lái)學(xué)習(xí)一下Struts2如何上傳文件。今天講的上傳文件的方式有三種:

  • 1以字節(jié)為單位傳輸文件;
  • 2Struts2封裝的一種方式;
  • 3以字符的方式傳輸文件。

其實(shí)這三種方式都差不多,都是將文件先從客戶端一臨時(shí)文件的形式,傳輸?shù)椒?wù)器的臨時(shí)文件夾下,然后在將該臨時(shí)文件復(fù)制到我們要上傳的目錄。另外,有一個(gè)需要注意,就是上傳過程中產(chǎn)生的這些臨時(shí)文件,Struts2不會(huì)自動(dòng)清理,所以我們需要手動(dòng)清理臨時(shí)文件,這一個(gè)下面的代碼中有提到。

用Action來(lái)完成我們上傳的核心功能:

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();  
        }  

        //驗(yàn)證文件大小及格式  
        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 {  
//          //關(guān)閉輸入、輸出流  
//          input.close();  
//          out.close();  
//          //刪除臨時(shí)文件  
//          upload.delete();  
//      }  

        //第二種上傳方式  
//      FileUtils.copyFile(upload, new File(uploadFile+"\\"+uploadFileName));  
//      //刪除臨時(shí)文件  
//      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();              
            //刪除臨時(shí)文件  
            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>    
    <!-- 上傳文件最大限制(如果為多文件上傳,則為多個(gè)文件的總大?。?-->    
    <constant name="struts.multipart.maxSize" value="40000000"></constant>    
    <!-- 存放上傳文件的臨時(shí)目錄 -->    
    <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">    
                單個(gè)文件的大小    
                <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>    

文件上傳的頁(yè)面:

<%@ 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"不對(duì)字符編碼。在使用包含文件上傳控件的表單時(shí),必須使用該值。 -->  
    <form action="file/upLoad" method="post" enctype="multipart/form-data">  
        <input name="upload" type="file">  
        <input name="btnUpload" type="submit" value="上傳">  
    </form>  
</body>  
</html>  

上傳文件之前,通常要判斷一下文件的大小及類型,上面有兩種方式來(lái)驗(yàn)證,一種是在Action里驗(yàn)證,一種是通過Struts2的攔截器驗(yàn)證。兩者選其一,選擇一個(gè)把另一個(gè)注釋掉即可。

另外,還有一個(gè)需要注意:上傳文件頁(yè)面中form的enctype屬性值,一定要設(shè)置成"multipart/form-data",否則就會(huì)出錯(cuò)。

OK,今天上傳文件就向大家介紹到這里,我們下篇博客再見!

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)