Loiane Groner, Brazilian, works as a Java/ Sencha evangelist. She has 7+ years of experience in web development. She is the ESJUG (Espirito Santo Java Users Group) and CampinasJUG (Campinas Java Users Group) leader and coordinator. Loiane is passionate about technology and programming. Also author of ExtJS 4 First Look book. Loiane is a DZone MVB and is not an employee of DZone and has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

ExtJS 4 File Upload + Spring MVC 3 Example

07.20.2011
| 31922 views |
  • submit to reddit

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 <a target="_blank" title="ExtJS" href="http://sencha.com/">ExtJS</a> 4 Form</title>
 
    <!-- <a target="_blank" title="Ext JS" href="http://sencha.com/">Ext JS</a> Files -->
    <link rel="stylesheet" type="text/css" href="/extjs4-file-upload-spring/<a target="_blank" title="extjs" href="http://sencha.com/">extjs</a>/resources/css/ext-all.css" />
    <script type="text/javascript" src="/extjs4-file-upload-spring/<a target="_blank" title="extjs" href="http://sencha.com/">extjs</a>/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 <a target="_blank" title="extjs" href="http://sencha.com/">extjs</a> 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 <a target="_blank" title="extjs" href="http://sencha.com/">extjs</a> 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 <a target="_blank" title="extjs" href="http://sencha.com/">extjs</a> 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 <a target="_blank" title="Ext JS" href="http://sencha.com/">Ext JS</a>
 *
 * @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! :)

 

From http://loianegroner.com/2011/07/extjs-4-file-upload-spring-mvc-3-example/

Published at DZone with permission of Loiane Groner, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Mitch Pronschinske replied on Thu, 2011/07/21 - 10:49am

I love your articles, Loiane!

Kevin Jordan replied on Fri, 2011/07/22 - 9:31am

Probably some slight nitpicking, but instead of letting on that you're using Apache's Commons FileUpload implementation in your class, you should probably use the MultipartFile interface. And also, unless you want it encapsulated inside an object for some reason (which would work well for putting things into a domain object, although MultipartFile wouldn't work too well in there) you can have the file and other things referenced directly in the method arguments via an annotation like @RequestParam("file").

Sirikant Noori replied on Fri, 2012/03/30 - 1:10pm

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.

Java Exam

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.