Ajax File Upload with ExtJS and Spring Framework
Posted on : 01-03-2010 | By : Loiane | In : ExtJS, Spring
16
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!





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 ………………….
[...] Grid на Spring и ExtJS Загрузка файла на Spring и ExtJS [...]
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?