ExtJS4 上传文件类型和大小的判断方法(实例)

源码下载:http://download.csdn.net/detail/biboheart/6036963

接本人博文《ExtJS4+strtus2文件上传实例》,在上面的基础上加上ExtJS上传文件前对文件类型和文件大小进行判断,不符合要求的将不能被上传。

PS:本人的原创博文是在开发中遇到的一些常见问题或难题作记录。由于我是初学者,知识面还远远不够,所以可能有许多地方并不是很好的解决方案,希望朋友你有想法能给予答复。谢谢!

开始本文的方案描述(源码稍后传上):

一直没找到ExtJS4 filefield控件的文件类型过滤与文件大小过滤的方法,本人E文水平较差,没能从官网得到这方面的资料。在网上也没有找到前人对此应用的方法介绍。实在想不出好的办法了,我就用js来完成此应用。

index.jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>UploadFileExample</title>
<link rel="stylesheet" type="text/css"
	href="ExtJS/resources/css/ext-all.css" />
<script type="text/javascript" src="ExtJS/ext-all.js"></script>
<script type="text/javascript" src="js/uploadFile.js"></script>
</head>
<body>
</body>
</html>

表单源码(UploadForm.js)代码:

Ext.define('AM.view.UploadForm',{
	extend:'Ext.panel.Panel',
	alias:'widget.uploadForm',
	initComponent: function() {
		Ext.apply(this, { 
			height: 140,
			width: 514,
			title: 'ExtJS4文件上传',
			layout: {
				type: 'fit'
			},
			items: [{
				xtype: 'form',
				frame: true,
				bodyPadding: 10,
				id:'usermanage-addprisoner-form',
				items: [{
					xtype: 'filefield',
					id:'id_fileField',
					name:'file',
					fieldLabel: '文件',
					buttonText: '选择文件',
					anchor: '100%'
				}],
				dockedItems: [{
					xtype: 'panel',
					frame: true,
					layout: {
						padding: '0 10',
						type:'auto'
					},
					dock: 'bottom',
					items: [{
						xtype: 'button',
						text: '上传',
						id:'addFile',
						padding:'0 10'
					}]
				}]
			}],
        }); 
		this.callParent(arguments);
	}
});

ExtJS控制层(UploadFile.js)代码:

Ext.define('AM.controller.UploadFile', {
    extend: 'Ext.app.Controller',
    views: [
		'UploadForm'
    ],
	init:function(){
		this.control({
			'uploadForm button[id=addFile]':{
				click:addFile
			},
			'uploadForm filefield[id=id_fileField]':{
				change:checkFile
			}
		});
	}
});

function addFile(o){
	var form = Ext.getCmp("usermanage-addprisoner-form").getForm();
	if(form.isValid()){
		form.submit({
			url:'/UploadFile/uploadFile',
			method:'POST',
			waitMsg:'正在上传',
			success:function(form, action){
				var data = Ext.JSON.decode(action.response.responseText);
                alert(data.message);
			},
			failure : function(form, action) {
				var data = Ext.JSON.decode(action.response.responseText);
				alert(data.message);
			}
		});
	};
};

function checkFile(o){
	//验证图片文件的正则
	var img_reg = /\.([jJ][pP][gG]){1}$|\.([jJ][pP][eE][gG]){1}$|\.([gG][iI][fF]){1}$|\.([pP][nN][gG]){1}$|\.([bB][mM][pP]){1}$/;
	if(!img_reg.test(o.value)){
		Ext.Msg.alert('提示','文件类型错误,请选择图片文件(jpe/jpeg/gif/png/bmp)');
		o.setRawValue('');
	}
	//取控件DOM对象
	var field = document.getElementById('id_fileField');
	//取控件中的input元素
	var inputs = field.getElementsByTagName('input');
	var fileInput = null;
	var il = inputs.length;
	//取出input 类型为file的元素
	for(var i = 0; i < il; i ++){
		if(inputs[i].type == 'file'){
			fileInput = inputs[i];
			break;
		}
	}
	if(fileInput != null){
		var fileSize = getFileSize(fileInput);
		//允许上传不大于1M的文件
		if(fileSize > 1000){
			Ext.Msg.alert('提示','文件太大,请选择小于1M的图片文件!');
			picItem.setRawValue('');
		}
	}
}

//计算文件大小,返回文件大小值,单位K
function getFileSize(target){
	var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
	var fs = 0;
	if (isIE && !target.files) {
		var filePath = target.value;
		var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
		var file = fileSystem.GetFile (filePath);
		fs = file.Size; 
	}else if(target.files && target.files.length > 0){
		fs = target.files[0].size;
	}else{
		fs = 0;
	}
	if(fs > 0){
		fs = fs / 1024;
	}
	return fs;
}

struts.xml请参照本人之前博文《ExtJS4+strtus2文件上传实例》;

action源码对上一次的有一点修改,但不是针对此文的应用而修改的。是上次应用中不够完善,作出的修改。如果只是本文应用,上面已经完成了方案。

public class UploadAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private File file;
	private String fileFileName; //文件名称
	private String fileContentType; //文件类型
	
	private boolean success;
	
	public String execute() throws Exception {
		return SUCCESS;
	}
	
	public void responseHtmlText(String text){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF8");
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
			return;
		}
	}
	
	public void responseJson(String jsonString){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/json;charset=UTF8");
		try {
			response.getWriter().write(jsonString);
		} catch (IOException e) {
			return;
		}
	}
	
	public void uploadFileUtils(){
		boolean success = false;
		success = true;
		if(file == null){
			responseHtmlText("{success:" + success + ",message:'服务端未收到文件'}");
			return;
		}
		String uploadPath = ServletActionContext.getServletContext().getRealPath("/upload");
		File savefile = new File(new File(uploadPath), fileFileName);
		if (!savefile.getParentFile().exists()){
			savefile.getParentFile().mkdirs();
		}
		try {
			FileUtils.copyFile(file, savefile);
		} catch (IOException e) {
			System.out.println("保存文件失败");
			responseHtmlText("{success:" + success + ",message:'保存文件失败'}");
			return;
		}
		responseHtmlText("{success:" + success + ",message:'文件上传成功'}");
	}
	
	@SuppressWarnings("resource")
	public void uploadFileIO(){
		boolean success = false;
		success = true;
		if(file == null){
			responseHtmlText("{success:" + success + ",message:'服务端未收到文件'}");
			return;
		}
		InputStream is = null;
		OutputStream os = null;
		//基于myFile创建一个文件输入流
		try {
			is = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			is = null;
			System.out.println("创建文件失败");
			responseHtmlText("{success:" + success + ",message:'创建文件失败'}");
			return;
		}
		//设置上传文件目录
		String uploadPath = ServletActionContext.getServletContext().getRealPath("/upload");
		System.out.println(uploadPath);
		//设置目标文件
		File savefile = new File(uploadPath, this.getFileFileName());
		if (!savefile.getParentFile().exists()){
			savefile.getParentFile().mkdirs();
		}
		//创建一个输出流
		try {
			os = new FileOutputStream(savefile);
		} catch (FileNotFoundException e) {
			os = null;
			System.out.println("创建输出流失败");
			responseHtmlText("{success:" + success + ",message:'创建输出流失败'}");
			return;
		}
		//设置缓存
		byte[] buffer = new byte[1024];
		int length = 0;
		//读取文件输出到toFile文件中
		try {
			while ((length = is.read(buffer)) > 0) {  
			    os.write(buffer, 0, length);  
			}
		} catch (IOException e) {
			System.out.println("读取文件失败");
			responseHtmlText("{success:" + success + ",message:'读取文件失败'}");
			return;
		}
		System.out.println("上传文件名" + fileFileName);  
        System.out.println("上传文件类型" + fileContentType);
        if(is != null){
        	try {
				is.close();
			} catch (IOException e) {
				System.out.println("关闭输入流失败");
				e.printStackTrace();
			}
        }
        if(os != null){
        	try {
				os.close();
			} catch (IOException e) {
				System.out.println("关闭输出流失败");
				return;
			}
        }
        responseHtmlText("{success:" + success + ",message:'文件上传成功'}");
	}
	
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public boolean isSuccess() {
		return success;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
}

其它不多说了,不明白的地方可以留言!

你可能感兴趣的:(源码,实例,extjs4)