Blog Archive

ExtJs 4 File Upload Java Servlet using Apache commons FileUpload Utility

The following example follows the ExtJs 4 MVC framework to create the File Upload form which makes a Java Servlet request to upload the file. The Java Servlet is uses the Apache commons FileUpload Utility.

FileUpload can be used in a number of different ways, depending upon the requirements of your application. In the simplest case, you will call a single method to parse the servlet request, and then process the list of items as they apply to your application. At the other end of the scale, you might decide to customize FileUpload to take full control of the way in which individual items are stored; for example, you might decide to stream the content into a database.

Click here to Download Apache Commons FileUpload jar file

ExtJs 4 File Upload using Apache commons FileUpload Utility
ExtJs 4 File Upload using Apache commons FileUpload Utility
ExtJs 4 File Upload using Apache commons FileUpload Utility

Step 1: Application starting point index.html

    <title>ExtJs 4 File Upload</title>

    <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
    <style type="text/css">
        .upload-icon {
            background: url('extjs/icons/fam/image_add.png') no-repeat 0 0 !important;
        .msg .x-box-mc {
        #msg-div {
        #msg-div .msg {
            border-radius: 8px;
            -moz-border-radius: 8px;
            background: #F6F6F6;
            border: 2px solid #ccc;
            margin-top: 2px;
            padding: 10px 15px;
            color: #555;
        #msg-div .msg h3 {
            margin: 0 0 8px;
            font-weight: bold;
            font-size: 15px;
        #msg-div .msg p {
            margin: 0;
    <script type="text/javascript" src="extjs/ext-all-debug.js"></script>
    <script type="text/javascript" src="app.js"></script>


Step 2: Application JavaScript file app.js

    enabled: true 

    name: 'SAMPLE',

    appFolder: 'app',
    controllers: [

    launch: function() {
        Ext.create('Ext.container.Viewport', {
            items: [
                    xtype: 'fileuploadform',

Step 3: JavaScript Source for file upload form view MyForm.js

Ext.define('SAMPLE.view.MyForm', {
    extend: 'Ext.form.Panel',
    alias : 'widget.fileuploadform',
    width: 500,
    frame: true,
    title: 'File Upload Form',
    bodyPadding: '10 10 0',

    defaults: {
        anchor: '100%',
        allowBlank: false,
        msgTarget: 'side',
        labelWidth: 75

    items: [{
        xtype: 'textfield',
        name: 'filename',
        fieldLabel: 'File Name'
        xtype: 'filefield',
        id: 'myFile',
        emptyText: 'Select a File to Upload',
        fieldLabel: 'Select a File',
        name: 'fileSelected',
        buttonText: '',
        buttonConfig: {
            iconCls: 'upload-icon'

    buttons: [{
        text: 'Upload',
        action: 'uploadFile'
        text: 'Reset Form',
        scope: this,
        handler: function() {

Step 4: JavaScript Source file for application controller FileUpload.js

Ext.define('SAMPLE.controller.FileUpload', {
            extend : '',

            //define the views
            views : ['MyForm'],

            //special method that is called when your application boots
            init : function() {
                //control function makes it easy to listen to events on 
                //your view classes and take some action with a handler function
                            //when the viewport is rendered
                            'viewport > panel' : {
                                render : this.onPanelRendered
                            //when you click Upload file button
                            'fileuploadform button[action=uploadFile]' : {
                                click : this.uploadFile   

            onPanelRendered : function() {
                //just a console log to show when the panel is rendered
                console.log('The panel was rendered');
            displayMessage : function(title, format){
                var msgCt;
                    msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
                var s = Ext.String.format.apply(String,, 1));
                var m = Ext.DomHelper.append(msgCt, this.createBox(title, s), true);
                m.slideIn('t').ghost("t", { delay: 1000, remove: true});
            createBox : function (t, s){
                   return '<div class="msg"><h3>' + t + '</h3><p>' + s + '</p></div>';

            uploadFile : function(button) {
                //just a console log to show when the file Upload starts
                console.log('File Upload in progress');
                var form = button.up('form').getForm();
                        url: 'FileUploadServlet',
                        waitMsg: 'Uploading your file...',
                        scope: this,
                        success: function(form, action){
                            // server responded with success = true
                            response = Ext.decode(action.response.responseText);
                                this.displayMessage('File Upload', 'Succefully uploaded to the Server');
                        failure: function(form, action){
                            if (action.failureType === CONNECT_FAILURE) {
                                   Ext.Msg.alert('Error', 'Status:'+action.response.status+': '+
                            if (action.failureType === SERVER_INVALID){
                                // server responded with success = false
                                Ext.Msg.alert('Invalid', action.result.errormsg);

Step 5: Web Application config file web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">
    <description>File Upload Servlet</description>

Step 6: File Upload Servlet

package com.as400samplecode;

import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String TMP_DIR_PATH = "/tempfiles";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH ="/files";
    private File destinationDir;

    public FileUploadServlet() {

    public void init(ServletConfig config) throws ServletException {
        String realPath = getServletContext().getRealPath(TMP_DIR_PATH);
        tmpDir = new File(realPath);
        if(!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
        if(!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //PrintWriter to send the JSON response back
        PrintWriter out = response.getWriter();
        //set content type
        DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
        //Set the size threshold, above which content will be stored on disk.
        fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
        //Set the temporary directory to store the uploaded files of size above threshold.

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            //Parse the request
            List items = uploadHandler.parseRequest(request);
            Iterator iterator = items.iterator();
            while(iterator.hasNext()) {
                FileItem item = (FileItem);
                //Handle Form Fields
                if(item.isFormField()) {
                    System.out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
                //Handle Uploaded files.
                else {
                    System.out.println("Field Name = "+item.getFieldName()+
                            ", File Name = "+item.getName()+
                            ", Content type = "+item.getContentType()+
                            ", File Size = "+item.getSize());
                    //Write file to the ultimate location.
                    File file = new File(destinationDir,item.getName());

                //Create a JSON object to send response
                JSONObject myObj = new JSONObject();
                //sets success to true
                myObj.put("success", true);
                //convert the JSON object to string and send the response back
        }catch(FileUploadException ex) {
            log("Error encountered while parsing the request",ex);
        } catch(Exception ex) {
            log("Error encountered while uploading file",ex);


ExtJs 4 File Upload using Apache commons FileUpload Utility


  1. Really helpful. Thx a lot!!


    1. - Các ngươi nghe theo sự sắp xếp của ta, vài ngày nữa ta sẽ luyện chế cho các ngươi một số đan dược, các ngươi đi hỗ trợ Đổng Đại Ngưu, ta đối với Đổng Đại Ngưu đúng là không yên tâm, các ngươi muốn hỗ trợ hắn thì nhanh chóng lập một cỗ lực lượng ở Quỷ Uyên.

      Nhạc Thành quyết định nói.
      đồng tâm
      game mu
      cho thuê phòng trọ
      cho thuê phòng trọ
      nhac san cuc manh
      tư vấn pháp luật qua điện thoại
      văn phòng luật
      số điện thoại tư vấn luật
      dịch vụ thành lập doanh nghiệp
      Đổng Đại Ngưu mặc dù không kém nhưng thực sự tổng thể lại vẫn kém Thác Ni Tư và Trần Bưu, đặc biệt là Trần Buư. Nhạc Thành nghĩ rằng Trần Bưu tâm cơ nặng nhất, người này đi vào trong Quỷ Uyên nhất định sẽ phát huy ưu thế lớn, thực lực cũng sẽ nhanh chóng tăng lên.

      Nhìn thấy Nhạc Thành đã định hai người cũng không nói thêm gì nữa, nhờ có Nhạc Thành luyện chế đan dược mà hai người đột nhiên cao hứng, dược hiệu luyện chế bọn họ đã thấy.

      Ngày hôm sau khi Hàn Nguyệt sắp xếp, Nhạc Thành đi tới khu học viên cũ, khu

  2. can you explain what this line mean

    action.failureType === CONNECT_FAILURE

    and this one

    action.failureType === SERVER_INVALID

    what is value of CONNECT_FAILURE and SERVER_INVALID exactly

  3. We are offering website service or website design!! Contact us for more info!!

    website designs service