首页 > 其他分享 >extjs4,spring mvc3上传文件

extjs4,spring mvc3上传文件

时间:2022-12-05 13:02:29浏览次数:65  
标签:return stream success mvc3 spring byteread file extjs4 public


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

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

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

</head>
<body>

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


<div id="fi-form" style="padding:25px;"></div>
</body>

2 EXTjs的文件
   Ext.onReady(function(){

    Ext.create('Ext.form.Panel', {
        title: 'File Uploader',
        width: 400,
        bodyPadding: 10,
        frame: true,
        renderTo: 'fi-form',   
        items: [{
            xtype: 'filefield',
            name: 'file',
            fieldLabel: 'File',
            labelWidth: 50,
            msgTarget: 'side',
            allowBlank: false,
            anchor: '100%',
            buttonText: 'Select a File...'
        }],

        buttons: [{
            text: 'Upload',
            handler: function() {
                var form = this.up('form').getForm();
                if(form.isValid()){
                    form.submit({
                        url: 'upload.action',
                        waitMsg: 'Uploading your file...',
                        success: function(fp, o) {
                            Ext.Msg.alert('Success', 'Your file has been uploaded.');
                        }
                    });
                }
            }
        }]
    });

});

3 上传文件的bean
   

1. import
2.
3.
4. public class
5.
6. private
7.
8. public
9. return
10. }
11.
12. public void
13. this.file = file;
14. }
15. }
16.
17.

import org.springframework.web.multipart.commons.CommonsMultipartFile;


public class FileUploadBean {

private CommonsMultipartFile file;

public CommonsMultipartFile getFile() {
return file;
}

public void setFile(CommonsMultipartFile file) {
this.file = file;
}
}



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


1. public class
2.
3. private boolean
4.
5. public boolean
6. return
7. }
8. public void setSuccess(boolean
9. this.success = success;
10. }
11.
12. public
13. return "{success:"+this.success+"}";
14. }
15. }

public class ExtJSFormResult {

private boolean success;

public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}

public String toString(){
return "{success:"+this.success+"}";
}
}


  这里其实是返回是否成功



5 controller层


  

1. @Controller
2. @RequestMapping(value = "/upload.action")
3. public class
4.
5. @RequestMapping(method = RequestMethod.POST)
6. public @ResponseBody
7.
8. new
9.
10. if
11. for(ObjectError error : result.getAllErrors()){
12. "Error: " + error.getCode() + " - "
13. }
14.
15. //set extjs return - error
16. false);
17.
18. return
19. }
20.
21. // Some type of file processing...
22. "-------------------------------------------");
23. "Test upload: "
24. "-------------------------------------------");
25. if(uploadItem.getFile().getSize()>0){
26. try
27. "D://",uploadItem.getFile().getOriginalFilename());
28. catch
29. System.out.println(e.getMessage());
30. return null;
31. }
32. }
33. //set extjs return - sucsess
34. true);
35.
36. return
37. }
38.
39. /* **保存文件
40.
41. * @param stream
42. * @param path
43. * @param filename
44. * @throws IOException
45. */
46. public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws
47. {
48. new FileOutputStream(path + "/"+ filename);
49. byte[] buffer=new byte[1024*1024];
50. int bytesum = 0;
51. int byteread = 0;
52. while ((byteread=stream.read())!=-1)
53. {
54. bytesum+=byteread;
55.
56. 0,byteread);
57. fs.flush();
58.
59. }
60. fs.close();
61. stream.close();
62. }

@Controller
@RequestMapping(value = "/upload.action")
public class FileUploadController {

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

ExtJSFormResult extjsFormResult = new ExtJSFormResult();

if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}

//set extjs return - error
extjsFormResult.setSuccess(false);

return extjsFormResult.toString();
}

// Some type of file processing...
System.err.println("-------------------------------------------");
System.err.println("Test upload: " + uploadItem.getFile().getOriginalFilename());
System.err.println("-------------------------------------------");
if(uploadItem.getFile().getSize()>0){
try {
SaveFileFromInputStream(uploadItem.getFile().getInputStream(),"D://",uploadItem.getFile().getOriginalFilename());
} catch (IOException e) {
System.out.println(e.getMessage());
return null;
}
}
//set extjs return - sucsess
extjsFormResult.setSuccess(true);

return extjsFormResult.toString();
}

/* **保存文件

* @param stream
* @param path
* @param filename
* @throws IOException
*/
public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException
{
FileOutputStream fs=new FileOutputStream(path + "/"+ filename);
byte[] buffer=new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read())!=-1)
{
bytesum+=byteread;

fs.write(buffer,0,byteread);
fs.flush();

}
fs.close();
stream.close();
}


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



return extjsFormResult.toString();


  这两句返回给前端ext js处理。


  最后就是配置MVC了


​​


1. <!-- Activates various annotations to be detected in bean classes -->   
2. <context:annotation-config />
3.
4. this application for @Components
5. package="com.loiane"/>
6.
7. <!-- Configures Spring MVC -->
8. import resource="mvc-config.xml"/>
9.
10. <!-- Configure the multipart resolver -->
11. "multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
12. <!-- one of the properties available; the maximum file size in bytes -->
13. "maxUploadSize" value="100000"/>
14.
15. </bean>


<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />

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

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

<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>

</bean>


  设置文件大小限制



  一个很奇怪的问题是,在ie 7下,好象有点问题,待解决,但在firefox和chrome下都没问题,这个extjs 真怪,不用ext,普通的spring mvc是没问题的哦 


标签:return,stream,success,mvc3,spring,byteread,file,extjs4,public
From: https://blog.51cto.com/u_14230175/5911930

相关文章

  • Spring Boot注入静态变量
    SpringBoot注入静态变量@value或者@Autowired不能直接注入值给静态属性,spring不允许/不支持把值注入到静态变量中;spring支持set方法注入,我们可以利用非静态setter方法......
  • Spring
    组成SpringCore:核心容器,BeanFactory提供了组件生命周期的管理,组件的创建、装配,销毁等功能。SpringContext:实现了ApplicationContext接口,Spring的上下文,拓展了核心容......
  • 源码解析:Dubbo3 的 Spring 适配原理与初始化流程
    Dubbo国内影响力最大的开源框架之一,非常适合构建大规模微服务集群的,提供开发框架、高性能通信、丰富服务治理等能力。同时Dubbo无缝支持Spring、SpringBoot模式的开......
  • Spring Cloud Vault Config
    9.自定义要公开为属性源的机密后端SpringCloudVault使用基于属性的配置来创建键值和发现的秘密后端。​​PropertySource​​发现的后端提供bean来描述使用机密后端的......
  • Spring中获取request的几种方法,及其线程安全性分析
    前言本文将介绍在SpringMVC开发的web系统中,获取request对象的几种方法,并讨论其线程安全性。目录概述如何测试线程安全性方法1:Controller中加参数方法2:自动注入方法3......
  • 如何使用 Spring Cloud Zookeeper 进行服务发现和分布式配置
    该项目通过以下方式为SpringBoot应用程序提供Zookeeper集成自动配置并绑定到Spring环境和其他Spring编程模型习语。通过一些注释,您可以快速启用和配置常见模式......
  • springmvc注册fastJson报错
    原因:依赖版本问题这是我原本引入的依赖,版本是1.2.24<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId......
  • spring-boot-@Valid和@Validated详解
    ----------------------------------------------------------------------------------------在实际的项目开发中,经常会遇到对参数进行校验的场景,最常见的就是后端需要对......
  • spring学习小结之:hibernatetemplate,过度封装?
    边学spring,突然发现之前spring与hibernate结合的方式可以更厉害地封装,那就是用hibernateTemplate了,只需要改边userdao.java如下importorg.springfr......
  • spring mvc3及mvc 3.2中的异常处理小结
    在springmvc3中,处理异常的是试用exceptionresolver去做异常,先来个简单DEMO看下:1)自定义异常类publicclassSpringExceptionextendsRuntime......