Struts2文件上传之手动过滤类型与大小

uploadForm.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
	<form action="uploadAction" method="post" enctype="multipart/form-data"> 
		文件标题:<input type="text" name="title"><br>
		上传文件:<input type="file" name="upload"><br>
		<input type="submit" value="提交">
		<s:fielderror/>
	</form>
	
</body>
</html>


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>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.multipart.saveDir" value="/tmp"></constant>
    <package name="default" extends="struts-default">

        <action name="uploadAction" class="action.UploadAction">
        	<param name="allowTypes">image/bmp,image/png,image/gif,image/jpeg,image/pjpeg</param>
        	<!-- 动态设置Action的属性值 -->
        	<param name="savePath">/upload</param>
        	<!-- 上传失败后返回input逻辑视图 -->
        	<result name="input">/WEB-INF/content/uploadForm.jsp</result>
            <result>/WEB-INF/content/succ.jsp</result>
        </action>
        <action name="*">
        	<result>/WEB-INF/content/{1}.jsp</result>
        </action>
    </package>
</struts>


UploadAction.java:

package action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

	private String title;//文件标题 
	private File upload;//上传文件域
	private String uploadContentType;//上传文件类型
	private String uploadFileName;//上传文件名
	private String savePath;//从struts.xml里取得
	private String allowTypes;//允许上传的文件类型
	
	
	public String getAllowTypes() {
		return allowTypes;
	}
	public void setAllowTypes(String allowTypes) {
		this.allowTypes = allowTypes;
	}
	public String getSavePath() {
		return ServletActionContext.getRequest().getRealPath(savePath);
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	@Override
	public String execute() throws Exception {
		String filterResult = filterType(getAllowTypes().split(","));
		if(filterResult != null){
			addFieldError("upload", "您要上传的文件类型不正确!");
			return filterResult;
		}
		File uploadFile = getUpload();
		String filterLength = filterLength(uploadFile);
		if(filterLength != null){
			addFieldError("upload", "您要上传的文件超过大小!");
			return filterLength;
		}
		
		//随机文件名+后缀
		String newName = UUID.randomUUID()+uploadFileName.substring(uploadFileName.lastIndexOf("."));
		//以服务器的文件保存地址和随机文件名建立上传文件输出流
		FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+newName);
		FileInputStream fis = new FileInputStream(getUpload());
		byte[] buffer = new byte[1024];
		int len = 0;
		while((len = fis.read(buffer))>0){
			fos.write(buffer, 0, len);
		}
		setUploadFileName(newName);//设置上传文件名
		return SUCCESS;
	}
	
	/**
	 * 过滤文件类型
	 * @param types 系统所有允许上传的文件类型
	 * @return 如果上传文件的文件类型允许上传,则返回null,否则返回input字符串
	 */
	public String filterType(String[] types) {
		//获取希望上传的文件类型
		String fileType = getUploadContentType();
		for(String type : types){
			if (type.equals(fileType)) {
				return null;
			}
		}
		return INPUT;
	}
	
	/**
	 * 获取文件大小
	 * @param file
	 * @return
	 */
	public String filterLength(File file){
		long fileLen = file.length();
		System.out.println("fileLen="+fileLen);
		if(fileLen<1024*1024){//1M
			return null;
		}
		return INPUT;
	}
	
}


succ.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
	上传成功!<br>
	文件标题:<s:property value="title"/><br>
	文件为:<br><img src='upload/<s:property value="uploadFileName"/>'/><br>
	
</body>
</html>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值