Over a million developers have joined DZone.

ExtJS 4 File Upload + Spring MVC 3 Example

· Java Zone

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

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/

The Java Zone is brought to you in partnership with JetBrains.  Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}