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

<html>
<head>
    <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 {
            font-size:14px;
        }
        #msg-div {
            position:absolute;
            left:35%;
            top:10px;
            width:300px;
            z-index:20000;
        }
        #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;
        }
    </style>
   
    <script type="text/javascript" src="extjs/ext-all-debug.js"></script>
    <script type="text/javascript" src="app.js"></script>

</head>
<body></body>
</html>

Step 2: Application JavaScript file app.js

Ext.Loader.setConfig({ 
    enabled: true 
    });

Ext.application({
    name: 'SAMPLE',

    appFolder: 'app',
   
    controllers: [
                  'FileUpload'
              ],

    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() {
            this.reset();
        }
    }]
});

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

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

            //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
                this.control({
                   
                            //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;
                if(!msgCt){
                    msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
                }
                var s = Ext.String.format.apply(String, Array.prototype.slice.call(arguments, 1));
                var m = Ext.DomHelper.append(msgCt, this.createBox(title, s), true);
                m.hide();
                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();
                if(form.isValid()){
                    form.submit({
                        url: 'FileUploadServlet',
                        waitMsg: 'Uploading your file...',
                        scope: this,
                        success: function(form, action){
                            // server responded with success = true
                            response = Ext.decode(action.response.responseText);
                            if(response.success){
                                this.displayMessage('File Upload', 'Succefully uploaded to the Server');
                                form.reset();
                            }
                        },
                        failure: function(form, action){
                            if (action.failureType === CONNECT_FAILURE) {
                                   Ext.Msg.alert('Error', 'Status:'+action.response.status+': '+
                                action.response.statusText);
                            }
                            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="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ExtJs_File_Upload</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description>File Upload Servlet</description>
    <display-name>FileUploadServlet</display-name>
    <servlet-name>FileUploadServlet</servlet-name>
    <servlet-class>com.as400samplecode.FileUploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileUploadServlet</servlet-name>
    <url-pattern>/FileUploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

Step 6: File Upload Servlet FileUploadServlet.java

package com.as400samplecode;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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() {
        super();
    }

    public void init(ServletConfig config) throws ServletException {
       
        super.init(config);
        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
        response.setContentType("text/html");
       
        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.
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
       
            //Parse the request
            List items = uploadHandler.parseRequest(request);
            Iterator iterator = items.iterator();
            while(iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
               
                //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());
                    item.write(file);
                }

                //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
                out.println(myObj.toString());
                out.close();
               
            }
        }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


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.