免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3712 | 回复: 0
打印 上一主题 下一主题

extjs4,spring mvc3上传文件 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-07-27 14:44 |只看该作者 |倒序浏览
extjs4,spring mvc3上传文件



本文讲解下extjs4结合spring mvc3的注解完成上传文件的例子。

1 页面文件
  1. <!-- Ext JS Files -->
  2. <link rel="stylesheet" type="text/css" href="/extjs4-file-upload-spring/extjs/resources/css/ext-all.css" />
  3.     <script type="text/javascript" src="/extjs4-file-upload-spring/extjs/bootstrap.js"></script>

  4. <!-- file upload form -->
  5. <script src="/extjs4-file-upload-spring/js/file-upload.js"></script>

  6. </head>
  7. <body>

  8. Click on "Browse" button (image) to select a file and click on Upload button


  9. <div id="fi-form" style="padding:25px;"></div>
  10. </body>
复制代码
2 EXTjs的文件
  1.   Ext.onReady(function(){

  2.     Ext.create('Ext.form.Panel', {
  3.         title: 'File Uploader',
  4.         width: 400,
  5.         bodyPadding: 10,
  6.         frame: true,
  7.         renderTo: 'fi-form',   
  8.         items: [{
  9.             xtype: 'filefield',
  10.             name: 'file',
  11.             fieldLabel: 'File',
  12.             labelWidth: 50,
  13.             msgTarget: 'side',
  14.             allowBlank: false,
  15.             anchor: '100%',
  16.             buttonText: 'Select a File...'
  17.         }],

  18.         buttons: [{
  19.             text: 'Upload',
  20.             handler: function() {
  21.                 var form = this.up('form').getForm();
  22.                 if(form.isValid()){
  23.                     form.submit({
  24.                         url: 'upload.action',
  25.                         waitMsg: 'Uploading your file...',
  26.                         success: function(fp, o) {
  27.                             Ext.Msg.alert('Success', 'Your file has been uploaded.');
  28.                         }
  29.                     });
  30.                 }
  31.             }
  32.         }]
  33.     });

  34. });
复制代码
3 上传文件的bean
   
Java代码
  1. import org.springframework.web.multipart.commons.CommonsMultipartFile;


  2. public class FileUploadBean {

  3.         private CommonsMultipartFile file;

  4.         public CommonsMultipartFile getFile() {
  5.                 return file;
  6.         }

  7.         public void setFile(CommonsMultipartFile file) {
  8.                 this.file = file;
  9.         }
  10. }

复制代码
4 为了让extjs显示信息,再设计一个bean

Java代码
  1. public class ExtJSFormResult {

  2.         private boolean success;
  3.        
  4.         public boolean isSuccess() {
  5.                 return success;
  6.         }
  7.         public void setSuccess(boolean success) {
  8.                 this.success = success;
  9.         }
  10.        
  11.         public String toString(){
  12.                 return "{success:"+this.success+"}";
  13.         }
  14. }
复制代码
这里其实是返回是否成功

5 controller层
   
Java代码
  1. @Controller
  2. @RequestMapping(value = "/upload.action")
  3. public class FileUploadController {

  4.         @RequestMapping(method = RequestMethod.POST)
  5.         public @ResponseBody String create(FileUploadBean uploadItem, BindingResult result){

  6.                 ExtJSFormResult extjsFormResult = new ExtJSFormResult();
  7.                
  8.                 if (result.hasErrors()){
  9.                         for(ObjectError error : result.getAllErrors()){
  10.                                 System.err.println("Error: " + error.getCode() +  " - " + error.getDefaultMessage());
  11.                         }
  12.                        
  13.                         //set extjs return - error
  14.                         extjsFormResult.setSuccess(false);
  15.                        
  16.                         return extjsFormResult.toString();
  17.                 }

  18.                 // Some type of file processing...
  19.                 System.err.println("-------------------------------------------");
  20.                 System.err.println("Test upload: " + uploadItem.getFile().getOriginalFilename());
  21.                 System.err.println("-------------------------------------------");
  22.                  if(uploadItem.getFile().getSize()>0){                  
  23.                         try {   
  24.                             SaveFileFromInputStream(uploadItem.getFile().getInputStream(),"D://",uploadItem.getFile().getOriginalFilename());   
  25.                         } catch (IOException e) {   
  26.                             System.out.println(e.getMessage());   
  27.                             return null;   
  28.                         }   
  29.                     }   
  30.                 //set extjs return - sucsess
  31.                 extjsFormResult.setSuccess(true);
  32.                
  33.                 return extjsFormResult.toString();
  34.         }
  35.        
  36.         /* **保存文件   
  37.        
  38.            * @param stream   
  39.            * @param path   
  40.            * @param filename   
  41.            * @throws IOException   
  42.            */   
  43.           public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException   
  44.           {         
  45.            FileOutputStream fs=new FileOutputStream(path + "/"+ filename);
  46.            byte[]  buffer=new byte[1024*1024];
  47.            int bytesum = 0;   
  48.               int byteread = 0;
  49.                 while ((byteread=stream.read())!=-1)
  50.                 {
  51.                         bytesum+=byteread;
  52.                        
  53.                           fs.write(buffer,0,byteread);   
  54.                       fs.flush();   
  55.                        
  56.                 }
  57.                 fs.close();   
  58.                 stream.close();   
  59.           }   

复制代码
可以看到,当出现错误时,extjsFormResult.setSuccess(false);

return extjsFormResult.toString();
  这两句返回给前端ext js处理。
  最后就是配置MVC了
  
Java代码
  1. <!-- Activates various annotations to be detected in bean classes -->
  2.     <context:annotation-config />

  3.     <!-- Scans the classpath of this application for @Components to deploy as beans -->
  4.     <context:component-scan base-package="com.loiane"/>

  5.     <!-- Configures Spring MVC -->
  6.     <import resource="mvc-config.xml"/>

  7.     <!-- Configure the multipart resolver -->
  8.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  9.         <!-- one of the properties available; the maximum file size in bytes -->
  10.         <property name="maxUploadSize" value="100000"/>
  11.       
  12.     </bean>
复制代码
设置文件大小限制

  一个很奇怪的问题是,在ie 7下,好象有点问题,待解决,但在firefox和chrome下都没问题,这个extjs 真怪,不用ext,普通的spring mvc是没问题的哦
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP