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

来源:互联网 发布:淘宝街拍欧美 编辑:程序博客网 时间:2024/06/09 15:02

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

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

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

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

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

index.jsp代码:

[html] view plaincopyprint?
  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>  

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

[javascript] view plaincopyprint?
  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. });  

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

[javascript] view plaincopyprint?
  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. }  

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

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

[java] view plaincopyprint?
  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. }  

其它不多说了,不明白的地方可以留言!
 
原文地址:http://blog.csdn.net/biboheart/article/details/10579175
 
0 0
原创粉丝点击