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

本文介绍如何使用ExtJS4实现文件上传功能,并在上传前进行文件类型和大小的验证。通过JavaScript自定义验证逻辑,确保只有符合要求的文件才能上传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码下载:http://download.youkuaiyun.com/detail/biboheart/6036963

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

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

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

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

index.jsp代码:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%  
  4.     String path = request.getContextPath();  
  5.     String basePath = request.getScheme() + "://"  
  6.             + request.getServerName() + ":" + request.getServerPort()  
  7.             + path + "/";  
  8. %>  
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  10. <html>  
  11. <head>  
  12. <base href="<%=basePath%>" />  
  13. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  14. <title>UploadFileExample</title>  
  15. <link rel="stylesheet" type="text/css"  
  16.     href="ExtJS/resources/css/ext-all.css" />  
  17. <script type="text/javascript" src="ExtJS/ext-all.js"></script>  
  18. <script type="text/javascript" src="js/uploadFile.js"></script>  
  19. </head>  
  20. <body>  
  21. </body>  
  22. </html>  
<%@ 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)代码:

[javascript] view plain copy print ?
  1. Ext.define('AM.view.UploadForm',{  
  2.     extend:'Ext.panel.Panel',  
  3.     alias:'widget.uploadForm',  
  4.     initComponent: function() {  
  5.         Ext.apply(this, {   
  6.             height: 140,  
  7.             width: 514,  
  8.             title: 'ExtJS4文件上传',  
  9.             layout: {  
  10.                 type: 'fit'  
  11.             },  
  12.             items: [{  
  13.                 xtype: 'form',  
  14.                 frame: true,  
  15.                 bodyPadding: 10,  
  16.                 id:'usermanage-addprisoner-form',  
  17.                 items: [{  
  18.                     xtype: 'filefield',  
  19.                     id:'id_fileField',  
  20.                     name:'file',  
  21.                     fieldLabel: '文件',  
  22.                     buttonText: '选择文件',  
  23.                     anchor: '100%'  
  24.                 }],  
  25.                 dockedItems: [{  
  26.                     xtype: 'panel',  
  27.                     frame: true,  
  28.                     layout: {  
  29.                         padding: '0 10',  
  30.                         type:'auto'  
  31.                     },  
  32.                     dock: 'bottom',  
  33.                     items: [{  
  34.                         xtype: 'button',  
  35.                         text: '上传',  
  36.                         id:'addFile',  
  37.                         padding:'0 10'  
  38.                     }]  
  39.                 }]  
  40.             }],  
  41.         });   
  42.         this.callParent(arguments);  
  43.     }  
  44. });  
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)代码:

[javascript] view plain copy print ?
  1. Ext.define('AM.controller.UploadFile', {  
  2.     extend: 'Ext.app.Controller',  
  3.     views: [  
  4.         'UploadForm'  
  5.     ],  
  6.     init:function(){  
  7.         this.control({  
  8.             'uploadForm button[id=addFile]':{  
  9.                 click:addFile  
  10.             },  
  11.             'uploadForm filefield[id=id_fileField]':{  
  12.                 change:checkFile  
  13.             }  
  14.         });  
  15.     }  
  16. });  
  17.   
  18. function addFile(o){  
  19.     var form = Ext.getCmp("usermanage-addprisoner-form").getForm();  
  20.     if(form.isValid()){  
  21.         form.submit({  
  22.             url:'/UploadFile/uploadFile',  
  23.             method:'POST',  
  24.             waitMsg:'正在上传',  
  25.             success:function(form, action){  
  26.                 var data = Ext.JSON.decode(action.response.responseText);  
  27.                 alert(data.message);  
  28.             },  
  29.             failure : function(form, action) {  
  30.                 var data = Ext.JSON.decode(action.response.responseText);  
  31.                 alert(data.message);  
  32.             }  
  33.         });  
  34.     };  
  35. };  
  36.   
  37. function checkFile(o){  
  38.     //验证图片文件的正则   
  39.     var img_reg = /\.([jJ][pP][gG]){1}$|\.([jJ][pP][eE][gG]){1}$|\.([gG][iI][fF]){1}$|\.([pP][nN][gG]){1}$|\.([bB][mM][pP]){1}$/;  
  40.     if(!img_reg.test(o.value)){  
  41.         Ext.Msg.alert('提示','文件类型错误,请选择图片文件(jpe/jpeg/gif/png/bmp)');  
  42.         o.setRawValue('');  
  43.     }  
  44.     //取控件DOM对象   
  45.     var field = document.getElementById('id_fileField');  
  46.     //取控件中的input元素   
  47.     var inputs = field.getElementsByTagName('input');  
  48.     var fileInput = null;  
  49.     var il = inputs.length;  
  50.     //取出input 类型为file的元素   
  51.     for(var i = 0; i < il; i ++){  
  52.         if(inputs[i].type == 'file'){  
  53.             fileInput = inputs[i];  
  54.             break;  
  55.         }  
  56.     }  
  57.     if(fileInput != null){  
  58.         var fileSize = getFileSize(fileInput);  
  59.         //允许上传不大于1M的文件   
  60.         if(fileSize > 1000){  
  61.             Ext.Msg.alert('提示','文件太大,请选择小于1M的图片文件!');  
  62.             picItem.setRawValue('');  
  63.         }  
  64.     }  
  65. }  
  66.   
  67. //计算文件大小,返回文件大小值,单位K   
  68. function getFileSize(target){  
  69.     var isIE = /msie/i.test(navigator.userAgent) && !window.opera;  
  70.     var fs = 0;  
  71.     if (isIE && !target.files) {  
  72.         var filePath = target.value;  
  73.         var fileSystem = new ActiveXObject("Scripting.FileSystemObject");  
  74.         var file = fileSystem.GetFile (filePath);  
  75.         fs = file.Size;   
  76.     }else if(target.files && target.files.length > 0){  
  77.         fs = target.files[0].size;  
  78.     }else{  
  79.         fs = 0;  
  80.     }  
  81.     if(fs > 0){  
  82.         fs = fs / 1024;  
  83.     }  
  84.     return fs;  
  85. }  
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源码对上一次的有一点修改,但不是针对此文的应用而修改的。是上次应用中不够完善,作出的修改。如果只是本文应用,上面已经完成了方案。

  1. public class UploadAction extends ActionSupport{  
  2.     private static final long serialVersionUID = 1L;  
  3.     private File file;  
  4.     private String fileFileName; //文件名称   
  5.     private String fileContentType; //文件类型   
  6.       
  7.     private boolean success;  
  8.       
  9.     public String execute() throws Exception {  
  10.         return SUCCESS;  
  11.     }  
  12.       
  13.     public void responseHtmlText(String text){  
  14.         HttpServletResponse response = ServletActionContext.getResponse();  
  15.         response.setContentType("text/html;charset=UTF8");  
  16.         try {  
  17.             response.getWriter().write(text);  
  18.         } catch (IOException e) {  
  19.             return;  
  20.         }  
  21.     }  
  22.       
  23.     public void responseJson(String jsonString){  
  24.         HttpServletResponse response = ServletActionContext.getResponse();  
  25.         response.setContentType("text/json;charset=UTF8");  
  26.         try {  
  27.             response.getWriter().write(jsonString);  
  28.         } catch (IOException e) {  
  29.             return;  
  30.         }  
  31.     }  
  32.       
  33.     public void uploadFileUtils(){  
  34.         boolean success = false;  
  35.         success = true;  
  36.         if(file == null){  
  37.             responseHtmlText("{success:" + success + ",message:'服务端未收到文件'}");  
  38.             return;  
  39.         }  
  40.         String uploadPath = ServletActionContext.getServletContext().getRealPath("/upload");  
  41.         File savefile = new File(new File(uploadPath), fileFileName);  
  42.         if (!savefile.getParentFile().exists()){  
  43.             savefile.getParentFile().mkdirs();  
  44.         }  
  45.         try {  
  46.             FileUtils.copyFile(file, savefile);  
  47.         } catch (IOException e) {  
  48.             System.out.println("保存文件失败");  
  49.             responseHtmlText("{success:" + success + ",message:'保存文件失败'}");  
  50.             return;  
  51.         }  
  52.         responseHtmlText("{success:" + success + ",message:'文件上传成功'}");  
  53.     }  
  54.       
  55.     @SuppressWarnings("resource")  
  56.     public void uploadFileIO(){  
  57.         boolean success = false;  
  58.         success = true;  
  59.         if(file == null){  
  60.             responseHtmlText("{success:" + success + ",message:'服务端未收到文件'}");  
  61.             return;  
  62.         }  
  63.         InputStream is = null;  
  64.         OutputStream os = null;  
  65.         //基于myFile创建一个文件输入流   
  66.         try {  
  67.             is = new FileInputStream(file);  
  68.         } catch (FileNotFoundException e) {  
  69.             is = null;  
  70.             System.out.println("创建文件失败");  
  71.             responseHtmlText("{success:" + success + ",message:'创建文件失败'}");  
  72.             return;  
  73.         }  
  74.         //设置上传文件目录   
  75.         String uploadPath = ServletActionContext.getServletContext().getRealPath("/upload");  
  76.         System.out.println(uploadPath);  
  77.         //设置目标文件   
  78.         File savefile = new File(uploadPath, this.getFileFileName());  
  79.         if (!savefile.getParentFile().exists()){  
  80.             savefile.getParentFile().mkdirs();  
  81.         }  
  82.         //创建一个输出流   
  83.         try {  
  84.             os = new FileOutputStream(savefile);  
  85.         } catch (FileNotFoundException e) {  
  86.             os = null;  
  87.             System.out.println("创建输出流失败");  
  88.             responseHtmlText("{success:" + success + ",message:'创建输出流失败'}");  
  89.             return;  
  90.         }  
  91.         //设置缓存   
  92.         byte[] buffer = new byte[1024];  
  93.         int length = 0;  
  94.         //读取文件输出到toFile文件中   
  95.         try {  
  96.             while ((length = is.read(buffer)) > 0) {    
  97.                 os.write(buffer, 0, length);    
  98.             }  
  99.         } catch (IOException e) {  
  100.             System.out.println("读取文件失败");  
  101.             responseHtmlText("{success:" + success + ",message:'读取文件失败'}");  
  102.             return;  
  103.         }  
  104.         System.out.println("上传文件名" + fileFileName);    
  105.         System.out.println("上传文件类型" + fileContentType);  
  106.         if(is != null){  
  107.             try {  
  108.                 is.close();  
  109.             } catch (IOException e) {  
  110.                 System.out.println("关闭输入流失败");  
  111.                 e.printStackTrace();  
  112.             }  
  113.         }  
  114.         if(os != null){  
  115.             try {  
  116.                 os.close();  
  117.             } catch (IOException e) {  
  118.                 System.out.println("关闭输出流失败");  
  119.                 return;  
  120.             }  
  121.         }  
  122.         responseHtmlText("{success:" + success + ",message:'文件上传成功'}");  
  123.     }  
  124.       
  125.     public File getFile() {  
  126.         return file;  
  127.     }  
  128.     public void setFile(File file) {  
  129.         this.file = file;  
  130.     }  
  131.     public boolean isSuccess() {  
  132.         return success;  
  133.     }  
  134.     public void setSuccess(boolean success) {  
  135.         this.success = success;  
  136.     }  
  137.     public String getFileContentType() {  
  138.         return fileContentType;  
  139.     }  
  140.     public void setFileContentType(String fileContentType) {  
  141.         this.fileContentType = fileContentType;  
  142.     }  
  143.   
  144.     public String getFileFileName() {  
  145.         return fileFileName;  
  146.     }  
  147.   
  148.     public void setFileFileName(String fileFileName) {  
  149.         this.fileFileName = fileFileName;  
  150.     }  
  151. }  
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;
	}
}

其它不多说了,不明白的地方可以留言!
 
原文地址: http://blog.youkuaiyun.com/biboheart/article/details/10579175
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值