Featured Posts

My DeveloperWorks: What's life like for a female Java... Just wanted to share with you my interview on Valerie's My developerWorks blog: Interview with Loiane Groner, Java developer in Brazil. I'm very happy, because this interview...

Readmore

Getting started with ExtJS in your J2EE project This tutorial will walk through how to get an Ext JS installation up and running quickly in your java (J2EE) project. Level: Basic This is the screenshot of this tutorial: First,...

Readmore

Tutorial: Getting Started with Spring Security This tutorial will cover a basic scenario where it  integrates Spring Security, using database-backed authentication, into an existing Spring web application. Spring...

Readmore

Integrating Spring Security with ExtJS Login Page This tutorial will walk through how to configure ExtJS Login form (Ajax login form) instead of default Spring Security login.jsp. Instead of using login.jsp from spring...

Readmore

Loiane Groner Rss

Ajax File Upload with ExtJS and Spring Framework

Posted on : 01-03-2010 | By : Loiane | In : ExtJS, Spring

2

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?

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!

  • Share/Bookmark