struts2文件上傳類型的過濾

第一種解決方案:

1.手動實現文件過濾:

判斷上傳的文件是否在允許的範圍內
定義該Action允許上傳的文件類型 private String allowTypes;
利用Struts2的輸入效驗判斷用戶的輸入的文件是否合理

UploadAction.java

package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String title;
	private File uploadfile;
	private String uploadfileContentType;
	private String uploadfileFileName;
	private String savePath;
	private String allowType;//定義該Action允許上傳的文件類型
	
	public boolean check(String type){
    	String[] types=allowType.split(",");
    	for(String s:types){
    		if(s.equals(type)){
    			return true;
    		}
    	}
		return false;
    	
    }
    public void  validate(){
    	boolean b=check(uploadfileContentType);
    	if(!b){
    		addFieldError("upload","上傳文件錯誤");
    	}
    }
	public String getAllowType() {
		return allowType;
	}

	public void setAllowType(String allowType) {
		this.allowType = allowType;
	}

	public String upload()  throws  Exception {
		
		
		FileInputStream fis = new FileInputStream(getUploadfile());
        FileOutputStream  fos=new FileOutputStream(getSavePath()+"\\"+getUploadfileFileName());
        byte[] buffer=new byte[1024];
        int len=0;
        while((len=fis.read(buffer))>0){
        	fos.write(buffer,0,len);
        }
        fos.close();
        fis.close();
        
		return SUCCESS;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}


	public File getUploadfile() {
		return uploadfile;
	}

	public void setUploadfile(File uploadfile) {
		this.uploadfile = uploadfile;
	}

	public String getUploadfileContentType() {
		return uploadfileContentType;
	}

	public void setUploadfileContentType(String uploadfileContentType) {
		this.uploadfileContentType = uploadfileContentType;
	}

	public String getUploadfileFileName() {
		return uploadfileFileName;
	}

	public void setUploadfileFileName(String uploadfileFileName) {
		this.uploadfileFileName = uploadfileFileName;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);//得到絕對路徑
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

}

struts.xml

<?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="hello" namespace="/hello" extends="struts-default">
		<action name="login" class="action.UploadAction" method="upload">
			<!-- 設置允許上傳的文件類型 -->
		        <param name="allowType">image/x-png,file/txt,image/jpeg</param>
			
			<param name="savePath">/uploadFiles</param>
			<result name="success">
				/success.jsp
			</result>
			<result name="input">
				/index.jsp
			</result>
		</action>
	</package>
</struts>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib  prefix="s"  uri="/struts-tags"%>>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  <s:fielderror/>
    <form action="/Upload-1/hello/login"  method="post"   enctype="multipart/form-data">
    文件名:<input  type="text"  name="title"/>
    文件:<input  type="file"  name="uploadfile"/>
<input  type="submit"/>
    </form>
  </body>
</html>

success.jsp

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

  </head>
  
  <%
String path = request.getContextPath();
  System.out.println(path);
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
System.out.println(basePath);
%>
  <body>
  上傳成功!<br>
  文件標題:<s:property  value="title"/><br>
  文件爲:<img  src="<%=basePath%><s:property  value="'uploadFiles/'+uploadfileFileName"/>"/><br>
  </body>
</html>

第二種解決方案:

2.攔截器實現文件過濾:

配置fileUpload攔截器兩個參數:
allowedTypes:允許上傳文件的類型,多個值用,分開
maximumSize:允許上傳文件的大小,單位字節。

UploadAction.java

package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String title;
	private File uploadfile;
	private String uploadfileContentType;
	private String uploadfileFileName;
	private String savePath;
	private String allowedTypes;
	
	
        public String getAllowedTypes() {
		return allowedTypes;
	}
	public void setAllowedTypes(String allowedTypes) {
		this.allowedTypes = allowedTypes;
	}

	public String upload()  throws  Exception {
		
		
		FileInputStream fis = new FileInputStream(getUploadfile());
        FileOutputStream  fos=new FileOutputStream(getSavePath()+"\\"+getUploadfileFileName());
        byte[] buffer=new byte[1024];
        int len=0;
        while((len=fis.read(buffer))>0){
        	fos.write(buffer,0,len);
        }
        fos.close();
        fis.close();
        
		return SUCCESS;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}


	public File getUploadfile() {
		return uploadfile;
	}

	public void setUploadfile(File uploadfile) {
		this.uploadfile = uploadfile;
	}

	public String getUploadfileContentType() {
		return uploadfileContentType;
	}

	public void setUploadfileContentType(String uploadfileContentType) {
		this.uploadfileContentType = uploadfileContentType;
	}

	public String getUploadfileFileName() {
		return uploadfileFileName;
	}

	public void setUploadfileFileName(String uploadfileFileName) {
		this.uploadfileFileName = uploadfileFileName;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);//得到絕對路徑
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

}

struts.xml

<?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="hello" namespace="/hello" extends="struts-default">
		<action name="login" class="action.UploadAction" method="upload">
			
			 <interceptor-ref name="fileUpload">
			   <param name="allowedTypes">image/x-png,image/gif,image/jpeg</param>
			   <param name="maximumSize">20000000</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref> 
			<param name="savePath">/uploadFiles</param>
			<result name="success">
				/success.jsp
			</result>
			<result name="input">
				/index.jsp
			</result>
		</action>
	</package>
</struts>



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