ExtJS 4 File Upload + Spring MVC 3 Example
This tutorial will walk you through out how to use the Ext JS 4 File Upload Field in the front end and Spring MVC 3 in the back end.
This tutorial is also an update for the tutorial Ajax File Upload with ExtJS and Spring Framework, implemented with Ext JS 3 and Spring MVC 2.5.
Ext JS File Upload Form
First, we will need the Ext JS 4 File upload form. This one is the same as showed in Ext JS 4 docs.
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.');
}
});
}
}
}]
});
});
HTML Page
Then in the HTML page, we will have a div where we are going to render the Ext JS form. This page also contains the required javascript imports:
<html>
<head>
<title>Spring FileUpload Example with ExtJS 4 Form</title>
<!-- 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>
<p>Click on "Browse" button (image) to select a file and click on Upload button</p>
<div id="fi-form" style="padding:25px;"></div>
</body>
</html>
FileUpload Bean
We will also need a FileUpload Bean to represent the file as a multipart file:
package com.loiane.model;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
/**
* Represents file uploaded from extjs form
*
* @author Loiane Groner
* http://loiane.com
* http://loianegroner.com
*/
public class FileUploadBean {
private CommonsMultipartFile file;
public CommonsMultipartFile getFile() {
return file;
}
public void setFile(CommonsMultipartFile file) {
this.file = file;
}
}
File Upload Controller
Then we will need a controller. This one is implemented with Spring MVC 3.
package com.loiane.controller;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.loiane.model.ExtJSFormResult;
import com.loiane.model.FileUploadBean;
/**
* Controller - Spring
*
* @author Loiane Groner
* http://loiane.com
* http://loianegroner.com
*/
@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("-------------------------------------------");
//set extjs return - sucsess
extjsFormResult.setSuccess(true);
return extjsFormResult.toString();
}
Ext JS Form Return
Some people asked me how to return something to the form to display a message to the user. We can implement a POJO with a success property. The success property is the only thing Ext JS needs as a return:
package com.loiane.model;
/**
* A simple return message for Ext JS
*
* @author Loiane Groner
* http://loiane.com
* http://loianegroner.com
*/
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+"}";
}
}
Spring Config
Don’t forget to add the multipart file config in the Spring config file:
<!-- 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>
NullPointerException
I also got some questions about NullPointerException. Make sure the fileupload field name has the same name as the CommonsMultipartFile property in the FileUploadBean class:
ExtJS:
{
xtype: 'filefield',
name: 'file',
fieldLabel: 'File',
labelWidth: 50,
msgTarget: 'side',
allowBlank: false,
anchor: '100%',
buttonText: 'Select a File...'
}
Java:
public class FileUploadBean {
private CommonsMultipartFile file;
}
These properties ALWAYS have to match!
You can still use the Spring MVC 2.5 code with the Ext JS 4 code presented in this tutorial.
Download
You can download the source code from my Github repository (you can clone the project or you can click on the download button on the upper right corner of the project page): https://github.com/loiane/extjs4-file-upload-spring
You can also download the source code form the Google Code repository: http://code.google.com/p/extjs4-file-upload-spring/
Both repositories have the same source. Google Code is just an alternative.
Happy Coding!
Comments (28)
Links to this Post
- Choosing Java Frameworks for Performance | July 29, 2011
- JavaPins | August 24, 2011









I’ve been getting interested in how spring can manage JS initiated “remoting”, but it’s clumsy. Check DWR instead. We use extjs/dwr/spring for years, and it’s far better than any other similar solution
Hi,i download the code and run it,but get wrong,and i can not find the file which i uploaded
Hi jackyrong,
You have to add some logic to process your file on the Controller class – store it on a dabase or write the file in a directory.
This tutorial only shows how to do the upload, you have to do something with the file.
HI,THANS I’VE make the addtional code to complete the project,but when i run it on ie7,it’t show some javascript wrong,but it is find in firefox and chrome,why?
Hi jackyrong,
what is the error you are getting on IE?
and the error is :in the popup windows,it said :unhandle error on page:see console or log,
and at the button of the ie7 status bar,it showed:error:1-logged erros
and if you use it in ie 7,maybe you will find it
Could you have build script included as well, would help quite few new users of extjs & spring
Sure, will do that on the next examples.
Thanks for the tip!
Hi Loiane,
I have an application with 2 tabs.Each tab has a form and a search button which when clicked displays the grid below the form.What happens is When i click reset on tab2, tab1 search stops working in a way it fetches the data but the grid is not shown anymore.Any clue.
Many thanks.
Hi Loiane,
I get a error:
“You’re trying to decode and invalid JSON String: {success:true} “
Hi oulie,
Are you trying to execute the example above or is there something different in your code?
Hey Loiane….your example was good…I am getting an ERROR though in Firebug…”uncaught exception: You’re trying to decode an invalid JSON String: “…I have the exact same code as posted by you…
I tried a couple of things in vain to see if they’d work…such as adding ‘@component’ for the 2 model java classes…and adding a standardSubmit: true in the extjs for Panel…neither of these worked….please help
Follow up on the error message….looks like its getting a 404…..here’s the full error message…
uncaught exception: You’re trying to decode an invalid JSON String: Error 404–Not Found From RFC 2068 Hypertext Transfer Protocol — HTTP/1.1: 10.4.5 404 Not Found The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.If the server does not wish to make this information available to the client, the status code 403 (Forbidden) can be used instead. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address.
I just downloaded your project as is and deployed it….even that’s giving the same error message…just an fyi
cheetos,
Hi,
Thanks.
I’m not getting the error on my machine, but I’ll take a look at it.
There is problem with Spring 3 and Exts 4 integration. Because in case of IE 7/8.
File is submitting to server but it also throwing exception.
In case of PHP it is not throwing any exception.
check this
http://122.160.226.254:8080/promoteIt/login.jsp
user name shukla
password miks
Form containing file field thowing exception in IE but not in other browsers.
There is a error in IE 6/7/8 (Exception thrown not caught)
Here is solution :
Just replace controller ‘create’ function by this
public void create(FileUploadBean uploadItem, BindingResult result,HttpServletResponse response){ 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); response.setContentType(‘text/html’) ;
response.getWriter().write(extjsFormResult.toString()); response.flushBuffer(); return; } // Some type of file processing… System.err.println(“——————————————-”); System.err.println(“Test upload: ” + uploadItem.getFile().getOriginalFilename()); System.err.println(“——————————————-”); //set extjs return – sucsess extjsFormResult.setSuccess(true);response.setContentType(‘text/html’) ;
response.getWriter().write(extjsFormResult.toString());
response.flushBuffer();
return ; }
Thanks for the tip shubhanshu!
Good Tutorial,
I tried & got error like unhandle error on page; but when i add in mvc-config.xml, it working
needs to be added in mvc-config.xml file
org.springframework.web.servlet.view.JstlView
Hi,
I am new here, thank you for this tutorial, I just downloaded this example and run it in eclipse, selected a file and pressed upload, the please wait dialog box is taking forever ,never end, can you please help.
thanks
HI Majid,
Are you getting any exceptions?
response.setContentType(“text/html”);This is right!
Thanks Loiane, just tried it, it works like a charm.Great job.