Ajax File Upload with ExtJS and Spring Framework
This tutorial will walk you through how to implement an ajax file upload form using ExtJS on client side and Spring Framework on server side.
What are you going to need before start this tutorial?
- ExtJS
- Spring Framework (MVC) and its dependencies
- commons-io-1.4.jar
- commons-fileupload-1.2.jar
First, you need to implement the ExtJS File Upload form. You can use ExtJS File Upload example page to see how it looks like (I’m using third example).
Bellow is the form I implemented (or copied from ExtJS and adapted it to my needs – spring):
Ext.onReady(function(){
Ext.QuickTips.init();
var msg = function(title, msg){
Ext.Msg.show({
title: title,
msg: msg,
minWidth: 200,
modal: true,
icon: Ext.Msg.INFO,
buttons: Ext.Msg.OK
});
};
var fp = new Ext.FormPanel({
renderTo: 'fi-form',
fileUpload: true,
width: 500,
frame: true,
title: 'File Upload Form',
autoHeight: true,
bodyStyle: 'padding: 10px 10px 0 10px;',
labelWidth: 50,
defaults: {
anchor: '95%',
allowBlank: false,
msgTarget: 'side'
},
items: [{
xtype: 'fileuploadfield',
id: 'form-file',
emptyText: 'Select a File to import',
fieldLabel: 'File',
name: 'file',
buttonCfg: {
text: '',
iconCls: 'upload-icon'
}
}],
buttons: [{
text: 'Upload',
handler: function(){
if(fp.getForm().isValid()){
fp.getForm().submit({
url: 'fileUpload/import.action',
waitMsg: 'Uploading your file...',
success: function(fp, o){
msg('Success', 'Processed file on the server');
}
});
}
}
},{
text: 'Reset',
handler: function(){
fp.getForm().reset();
}
}]
});
});
And here is an example of how to use it (html page):
<html>
<head>
<title>Spring FileUpload Example with ExtJS Form</title>
<!-- Ext JS files -->
<link rel="stylesheet" type="text/css" href="/extjs-file-import-spring/ext-3.1.1/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="/extjs-file-import-spring/ext-3.1.1/examples/shared/examples.css" />
<link rel="stylesheet" type="text/css" href="/extjs-file-import-spring/ext-3.1.1/examples/ux/fileuploadfield/css/fileuploadfield.css"/>
<style type=text/css>
.upload-icon {
background: url('/extjs-file-import-spring/ext-3.1.1/examples/shared/icons/fam/image_add.png') no-repeat 0 0 !important;
}
</style>
<script src="/extjs-file-import-spring/ext-3.1.1/adapter/ext/ext-base.js"></script>
<script src="/extjs-file-import-spring/ext-3.1.1/ext-all.js"></script>
<script src="/extjs-file-import-spring/ext-3.1.1/examples/ux/fileuploadfield/FileUploadField.js"></script>
<!-- file upload form -->
<script src="/extjs-file-import-spring/js/file-upload.js"></script>
</head>
<body>
<h1>Spring File Upload Example Integrated with ExtJS FileUpload Form</h1>
<p>Click on "Browse" button (image) to select a file and click on Upload button</p>
<div id="fi-form"></div>
</body>
</html>
Before starting to code a FileUploadController, you are going to need a FileUploadBean:
package com.loiane.beans;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadBean {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
And here is my FileUploadController (I am simply storing the uploaded file in a directory in my hard drive – C:). You can add some validation or process the file in this class. You can also add some message to return to client side in case of success or failure.
package com.loiane.web;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.loiane.beans.FileUploadBean;
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
MultipartFile file = bean.getFile();
String fileName = null;
if (file == null) {
System.out.println("User Did not upload file");
}
else {
System.out.println("Uploaded File Name is :" + file.getOriginalFilename());
}
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
String root = "C:\\";
fileName = root + file.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0 , 10000))!=-1){
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
return null;
}
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
throws ServletException {
// to actually be able to convert Multipart instance to byte[]
// we have to register a custom editor
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
// now Spring knows how to handle multipart object and convert them
}
}
You also need to add this in your servelt.xml:
<!-- max upload size in bytes -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1000000"/>
</bean>
Very simple!
Here is the source code of my example project: http://github.com/loiane/extjs-file-import-spring
Happy coding!
Comments (35)
Links to this Post
- Maxim Dadynsky » Архив Блога » Применение ExtJs в Spring | May 6, 2010
- extjstutorial.org | May 8, 2011
- ExtJS 4 File Upload + Spring MVC 3 Example | Loiane Groner | July 18, 2011
- Technical Diary » Blog Archive » links for 2011-07-21 | September 14, 2011
- JavaPins | January 8, 2012









Muito bom esse uploader. Ainda acharei um para jQuery onde aceita uma action url como este.
Parabéns pelo blog, vou linkar este aqui também no meu.
;*
Thanks Washington!
[Portuguese-BR]
Pensei que tivesse isso em JQuery, o plugin é bem mais completo que ExtJS (pelo menos eu acho! ) Se achar, dá um toque!
[/Portuguese-BR]
I thought that was something like this in JQuery. If you find anything, please let me know.
Nice Post.
Cool! Thanks for sharing!
Thank you so much Loiane for your help, it will save me a lot of time and effort.
Julien
GREAT!!!!, i’m looking for something like this, very goog example step by step; excellent post thanks for sharing ………………….
Again. Nice Post… Thanks for sharing
Eternal thanks Loiane!!
Excellent post!! You are going to help thousand of people!!!
Hug and kisses from Chile!!
PS: I needed to download the spring-web.jar for the multipart bean. Here is the link if someone had the same problem http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadspringwebjar.htm
Implemente el ejercicio enteramente, pero consigo un error en el archivo Ext-all.js linea 7 caracter 102830. Alguna idea sobre que puedo estar haciendo mal?. Soy un novato en cuanto a la librería Extjs o Sencha.
I get an error on Ext-all.js line 7 character 102830. Any ideas?
@Cort – which ExtJS version are you using?
I’m using ext-3.2.1.
It’s solved now. =)
I try your example but I get an error “missing ) in parenthetical” all the time.. any idea what might be wrong?
Which ExtJS version are you using?
Wow, I just started to read ExtJs book. I found out just like reading a completely new language. My ultimate goal was to find a view technology for Springframework. I was just searching some of others code and all seem to have different technologies like richfaces, dwr etc. I started thinking I am starting to get old, because there are so many. And the book which i referred did all it’s serverside stuff in php. Then I thought would ExtJs be helpful enough when I become comfortable with it and try to implement it with Java. Then I saw your post. I downloaded the git version and it was great. Then I tried to write everything myself(copy), where I stumbled. But the problem I found out later was Apache Tomcat did not referesh change I made. So i had to undeploy it from Apache and then redeploy it. Now it’s so cool. You gave me motivation to complete Extjs book. At least FormPanel and other ajax stuff. Thank you very much
Thank you!
Great. You have many great articles. Thanks. Keep posting more great articles
I get an error on Ext-all.js line 7 character 102830. Any ideas?
I’m using extjs 3.2.1, and when a call upload controller, another web page is opened
could you help me please
@eliud
please get the last code of this component – uploader – from extjs website.
Nice examples. Great work!
I am using extjs 3.3.0. I got error in IE6, code is 100647. and SyntaxError Unexpected token < @extjs-file-import-spring:1 in Chrome.
Would you help me, please!
can u plz explain the example using the servlet and extjs for uploading the file
Great example! Could you please comment what needs to be done if one wants to add notes or other descriptions about the uploaded file?
i’m looking for some upload information,thanks a lot.
I tried this examples, however on the server side, the File object is coming as null. Can you please let me know the possible things to look at ?
Thanks.
Hi Rahul,
Please check a newer version of this tutorial. I also explain how to avoid this Nullpointer exception:
http://loianegroner.com/2011/07/extjs-4-file-upload-spring-mvc-3-example/
Thanks!
very nice.
l benefit from your demo thank U.
I try your example but I get an error “missing ) in parenthetical” all the time.. any idea what might be wrong?
Hi Oulie,
Pls try the newest example I postes about this same topic