JavaEE:Ext3与SpringMVC实现文件批量上传!

作者博客地址更换至CSDN,地址:http://blog.csdn.net/littlebrain4solving

 

Spring MVC文件上传实现,结合SwfUpload Flash插件;我这里采用的是Ext3的界面元素进行实现上传功能,如果其他朋友使用JQuery或者纯JS的可以参考以下代码的实现进行更换,或者直接查看SWFUpload的API.

好了,进入正题,首先下载swfupload:https://code.google.com/p/swfupload/

关键的文件只需要 swfupload.js , swfupload.swf

 

(*)步骤一:导入前台JS代码与CSS样式

<!-- 加入JS引用 -->
<
script type="text/javascript" src="swfupload.js"></script>
/*******************************************************************************************/
/*******************************        文件上传组件样式        *****************************/
/*******************************************************************************************/
.db-icn-delete {
    background-image: url( ../images/iconx/remove.png) !important;
}
.db-icn-upload {
    background-image: url( ../images/iconx/upload.gif) !important;
}
.db-icn-upload_ {
    background-image: url( ../images/iconx/upload_.png) !important;
}
.db-icn-add {
    background-image: url(../images/iconx/add.png) !important;
}
.db-icn-stop {
    background-image: url(../images/iconx/stop.png) !important;
}
.db-icn-cross {
    background-image: url(../images/iconx/cross.png) !important;
}
.db-icn-trash {
    background-image: url( ../images/iconx/trash_16.gif) !important;
}
.db-icn-upload-local {
    background-image: url( ../images/iconx/upload_local.png) !important;
}
.ux-cell-icon-delete {
    background: url(../images/iconx/delete.gif) no-repeat;
    height: 16px;
    cursor: pointer;
}
.ux-cell-icon-completed {
    background: url(../images/iconx/tick.gif) no-repeat;
    height: 16px;
}
.ux-cell-icon-clear {
    background: url(../images/iconx/bin_empty.png) no-repeat;
    height: 16px;
}
.ux-cell-color-gray {
    font-style:italic;
    text-decoration: line-through;
    color: gray;
}
.upload-progress-table {
    width: auto;
    border-collapse: collapse;
    margin-top: 7px;
    font: normal 11px tahoma, arial, verdana, sans-serif;
}
.upload-progress-table .upload-progress-label {
    width: 60px;
    text-align: left;
    padding: 2px 2px 2px 15px;
}
.upload-progress-table .upload-progress-value {
    width:150;
}
组件样式
Ext.ns('Eyeson.Components');
/**
 * @class Eyeson.Components.FileUploadDialog
 * @extends Ext.Window
 * 文件上传窗口
 */
Eyeson.Components.FileUploadDialog = Ext.extend(Ext.Window, {
    fileList : null,
    swfupload : null,
    progressBar : null,
    progressInfo : null,
    uploadInfoPanel : null,
    flashUrl : 'resources/swfupload/swfupload.swf',
    fileSize : '1024 KB' ,
    params : {} ,
    uploadUrl : '' ,
    constructor : function(config) {
        this.progressInfo = {
            filesTotal : 0,
            filesUploaded : 0,
            bytesTotal : 0,
            bytesUploaded : 0,
            currentCompleteBytes : 0,
            lastBytes : 0,
            lastElapsed : 1,
            lastUpdate : null,
            timeElapsed : 1
        };
        this.uploadInfoPanel = new Ext.Panel({
            region : 'north',
            height : 65,
            baseCls : '',
            collapseMode : 'mini',
            split : true,
            border : false
        });
        this.progressBar = new Ext.ProgressBar({text : '等待中 Warten 0 %'});
        var autoExpandColumnId = Ext.id('fileName');
        this.fileList = new Ext.grid.GridPanel({
            border : false,
            enableColumnMove : false,
            enableHdMenu : false,
            columns : [
                new Ext.grid.RowNumberer(),
                {header : '文件名' , width : 100, dataIndex : 'fileName', sortable : false, fixed : true, renderer : this.formatFileName, id : autoExpandColumnId},
                {header : '文件大小' , width : 80, dataIndex : 'fileSize', sortable : false, fixed : true, renderer : this.formatFileSize, align : 'right'},
                {header : '文件类型' , width : 60, dataIndex : 'fileType', sortable : false, fixed : true, renderer : this.formatIcon, align : 'center'},
                {header : '进度' , width : 100, dataIndex : '', sortable : false, fixed : true, renderer : this.formatProgressBar, align : 'center'},
                {
                    header : '&nbsp;',
                    width : 28,
                    dataIndex : 'fileState',
                    renderer : this.formatState,
                    sortable : false,
                    fixed : true,
                    align : 'center'
                }
            ],
            autoExpandColumn : autoExpandColumnId,
            ds : new Ext.data.SimpleStore({fields : ['fileId','fileName', 'fileSize','fileType','fileState']}),
            tbar : new Ext.Toolbar(),
            bbar : []
        });
        this.uploadInfoPanel.on('render',function(){
            this.getProgressTemplate().overwrite(this.uploadInfoPanel.body,{
                filesUploaded : 0,
                filesTotal : 0,
                bytesUploaded : '0 bytes',
                bytesTotal : '0 bytes',
                timeElapsed : '00:00:00',
                timeLeft : '00:00:00',
                speedLast : '0 bytes/s',
                speedAverage : '0 bytes/s'
            });
        },this);
        this.fileList.on('cellclick',function(grid, rowIndex, columnIndex, e){
            if(columnIndex == 5){
                var record = grid.getSelectionModel().getSelected();
                var fileId = record.data.fileId;
                var file = this.swfupload.getFile(fileId);
                if(file){
                    if(file.filestatus != SWFUpload.FILE_STATUS.CANCELLED){
                        this.swfupload.cancelUpload(fileId);
                        if(record.data.fileState != SWFUpload.FILE_STATUS.CANCELLED){
                            record.set('fileState',SWFUpload.FILE_STATUS.CANCELLED);
                            record.commit();
                            this.onCancelQueue(fileId);
                        }
                    }
                }
            }
        },this);
        this.fileList.on('render',function(){
            this.fileList.getBottomToolbar().add(this.progressBar);
            var tb = this.fileList.getTopToolbar();
            tb.add({
//                text : '添加文件 File hinz',
                tooltip : '添加文件' ,
                iconCls : 'db-icn-add'
            });
            tb.add('-');
            tb.add({
//                text : '开始上传 Start Hoch',
                iconCls : 'db-icn-upload_',
                tooltip : '开始上传',
                handler : this.startUpload,
                scope : this
            });
            tb.add('-');
            tb.add({
//                text : '停止上传 Stop Hoch',
                iconCls : 'db-icn-stop',
                tooltip : '停止上传',
                handler : this.stopUpload,
                scope : this
            });
            tb.add('-');
            tb.add({
//                text : '取消队列 Cancel',
                iconCls : 'db-icn-cross',
                tooltip : '取消队列',
                handler : this.cancelQueue,
                scope : this
            });
            tb.add('-');
            tb.add({
//                text : '清空列表 Liste leeren',
                iconCls : 'db-icn-trash',
                tooltip : '清空列表',
                handler : this.clearList,
                scope : this
            });
            tb.add('->');
            tb.add('<font color="red">注意:附件大小不能超过' + this.fileSize + '</font>');
            tb.doLayout();//extjs2.x版本中可不加这行代码
            var em = this.fileList.getTopToolbar().items.first().el.child('em');
            var placeHolderId = Eyeson.Common.Util.getUniqueID();
            em.setStyle({
                position : 'relative',
                display : 'block'
            });
            em.createChild({
                tag : 'div',
                id : placeHolderId
            });
            var settings = {
                upload_url : this.uploadUrl , //文件上传请求地址
                post_params : Ext.isEmpty(this.postParams) ? {} : this.postParams,//post提交时带到服务器的参数
                flash_url : Ext.isEmpty(this.flashUrl) ? 'http://www.swfupload.org/swfupload.swf' : this.flashUrl,//swfupload.swf文件地址 
                file_post_name : Ext.isEmpty(this.filePostName) ? 'myUpload' : this.filePostName,//这里很重要,默认值为'fileData',这里匹配action中的setMyFile 属性
                file_size_limit : Ext.isEmpty(this.fileSize) ? '100 MB' : this.fileSize,//上传文件体积上限,单位MB
                file_types : Ext.isEmpty(this.fileTypes) ? '*.*' : this.fileTypes,//允许上传的文件类型
                file_types_description : this.fileTypesDescription,//文件类型描述
                use_query_string : true,//设置为true的时候,SWFUpload以GET形式发送数据,如果为false,那么就以POST发送数据。
                debug : false,//是否显示调试信息
                button_width : '22',//添加文件按钮长度
                button_height : '20',//添加文件按钮高度
                button_placeholder_id : placeHolderId,//指定添加文件对象id
                button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,// 该SWF的背景是透明的,可以透过它看到背后的页面元素
                button_cursor : SWFUpload.CURSOR.HAND,//设置鼠标划过button时的光标状态。默认为SWFUpload.CURSOR.ARROW,如果设置为SWFUpload.CURSOR.HAND,则为手形
                custom_settings : {//自定义属性
                    scope_handler : this
                },
                file_queued_handler : this.onFileQueued,//当文件选择对话框关闭消失时,如果选择的文件成功加入上传队列,那么针对每个成功加入的文件都会触发一次该事件(N个文件成功加入队列,就触发N次此事件)。
                file_queue_error_handler : this.onQueueError,//this.onFileQueueError,//当选择文件对话框关闭消失时,如果选择的文件加入到上传队列中失败,那么针对每个出错的文件都会触发一次该事件(此事件和fileQueued事件是二选一触发,文件添加到队列只有两种可能,成功和失败)。文件添加队列出错的原因可能有:超过了上传大小限制,文件为零字节,超过文件队列数量限制,设置之外的无效文件类型。
                file_dialog_complete_handler : this.onFileDialogComplete,//当文件选取对话框关闭后触发的事件处理函数
                upload_start_handler : this.onUploadStart,//开始上传文件前触发的事件处理函数
                upload_progress_handler : this.onUploadProgress,//该事件由flash定时触发,提供三个参数分别访问上传文件对象、已上传的字节数,总共的字节数。因此可以在这个事件中来定时更新页面中的UI元素,以达到及时显示上传进度的效果。
                upload_error_handler : this.onUploadError,//无论什么时候,只要上传被终止或者没有成功完成,那么该事件都将被触发。
                upload_success_handler : this.onUploadSuccess,//文件上传成功后触发的事件处理函数,必须返回一个非空值,否则此事件不会被触发,随后的uploadComplete事件也无法执行。
                upload_complete_handler : this.onUploadComplete
            };
            this.swfupload = new SWFUpload(settings);
            this.swfupload.uploadStopped = false;
            Ext.get(this.swfupload.movieName).setStyle({
                position : 'absolute', 
                top : 0,
                left : -2
            });
            this.resizeProgressBar();
            this.on('resize', this.resizeProgressBar, this);
        },this);
        Eyeson.Components.FileUploadDialog.superclass.constructor.call(this, Ext.applyIf(config || {},{
            title : '文件上传',
            modal : true,
            split : true,
            layout : 'border',
            iconCls : 'db-icn-upload-local',
            width : 500,
            height : 450,
            minWidth : 450,
            minHeight : 400,
            resizable : false,
            closeAction : 'hide',
            buttons : [{text : '关闭' , handler : function(){this.hide()} , scope : this}],
            items : [this.uploadInfoPanel,{
                region : 'center',
                layout : 'fit',
                margins : '0 -1 0 -1',
                items : [this.fileList]
            }]}
        ));
    },
    resizeProgressBar : function() {
        this.progressBar.setWidth(this.el.getWidth() - 18);
    },
    startUpload : function() {
        if (this.swfupload) {
            this.swfupload.uploadStopped = false;
            var post_params = this.swfupload.settings.post_params;
            Ext.apply(post_params , this.params);
            this.swfupload.setPostParams(post_params);
            this.swfupload.startUpload();
        }
    },
    stopUpload : function(){
        if (this.swfupload) {
            this.swfupload.uploadStopped = true;
            this.swfupload.stopUpload();
        }
    },
    cancelQueue : function() {
        if (this.swfupload) {
            this.swfupload.stopUpload();
            var stats = this.swfupload.getStats();
            while (stats.files_queued > 0) {
                this.swfupload.cancelUpload();
                stats = this.swfupload.getStats();
            }
            this.fileList.getStore().each(function(record){
                switch(record.data.fileState){
                    case SWFUpload.FILE_STATUS.QUEUED:
                    case SWFUpload.FILE_STATUS.IN_PROGRESS:
                        record.set('fileState',SWFUpload.FILE_STATUS.CANCELLED);
                        record.commit();
                        this.onCancelQueue(record.data.fileId);
                        break;
                    default : 
                        break;
                }
            },this);
        }
    },
    clearList : function() {
        var store = this.fileList.getStore();
        store.each(function(record){
            if(record.data.fileState != SWFUpload.FILE_STATUS.QUEUED && record.data.fileState != SWFUpload.FILE_STATUS.IN_PROGRESS){
                store.remove(record);
            }
        });
    },
    getProgressTemplate : function(){
        var tpl = new Ext.Template(
                '<table class="upload-progress-table"><tbody>',
                    '<tr>' +
                        '<td class="upload-progress-label"><nobr>已上传数: </nobr></td>',
                        '<td class="upload-progress-value"><nobr>{filesUploaded} / {filesTotal}</nobr></td>',
                        '<td class="upload-progress-label"><nobr>上传状态 Status: </nobr></td>',
                        '<td class="upload-progress-value"><nobr>{bytesUploaded} / {bytesTotal}</nobr></td>' +
                    '</tr>',
                    '<tr>' +
                        '<td class="upload-progress-label"><nobr>已用时间:</nobr></td>',
                        '<td class="upload-progress-value"><nobr>{timeElapsed}</nobr></td>',
                        '<td class="upload-progress-label"><nobr>剩余时间:</nobr></td>',
                        '<td class="upload-progress-value"><nobr>{timeLeft}</nobr></td>' +
                    '</tr>',
                    '<tr>' +
                        '<td class="upload-progress-label"><nobr>当前速度:</nobr></td>',
                        '<td class="upload-progress-value"><nobr>{speedLast}</nobr></td>',
                        '<td class="upload-progress-label"><nobr>平均速度:</nobr></td>',
                        '<td class="upload-progress-value"><nobr>{speedAverage}</nobr></td>' +
                    '</tr>',
                '</tbody></table>');
        tpl.compile();
        return tpl;
    },
    updateProgressInfo : function(){
        this.getProgressTemplate().overwrite(this.uploadInfoPanel.body,this.formatProgress(this.progressInfo));
    },
    formatProgress : function(info) {
        var r = {};
        r.filesUploaded = String.leftPad(info.filesUploaded, 3, '&nbsp;');
        r.filesTotal = info.filesTotal;
        r.bytesUploaded = String.leftPad(Ext.util.Format.fileSize(info.bytesUploaded), 6, '&#160;');
        r.bytesTotal = Ext.util.Format.fileSize(info.bytesTotal);
        r.timeElapsed = this.formatTime(info.timeElapsed);
        r.speedAverage = Ext.util.Format.fileSize(Math.ceil(1000 * info.bytesUploaded / info.timeElapsed)) + '/s';
        r.timeLeft = this.formatTime((info.bytesUploaded === 0) ? 0 : info.timeElapsed * (info.bytesTotal - info.bytesUploaded) / info.bytesUploaded);
        var caleSpeed = 1000 * info.lastBytes / info.lastElapsed;
        r.speedLast = Ext.util.Format.fileSize(caleSpeed < 0 ? 0 : caleSpeed) + '/s';
        var p = info.bytesUploaded / info.bytesTotal;
        p = p || 0;
        this.progressBar.updateProgress(p, "上传中 " + Math.ceil(p * 100) + " %");
        return r;
    },
    formatTime : function(milliseconds) {
        var seconds = parseInt(milliseconds / 1000, 10);
        var s = 0;
        var m = 0;
        var h = 0;
        if (3599 < seconds) {
            h = parseInt(seconds / 3600, 10);
            seconds -= h * 3600;
        }
        if (59 < seconds) {
            m = parseInt(seconds / 60, 10);
            seconds -= m * 60;
        }
        m = String.leftPad(m, 2, '0');
        h = String.leftPad(h, 2, '0');
        s = String.leftPad(seconds, 2, '0');
        return h + ':' + m + ':' + s;
    },
    formatFileSize : function(_v,celmeta,record){
        return '<div id="fileSize_' + record.data.fileId + '">' + Ext.util.Format.fileSize(_v) + '</div>';
    },
    formatFileName : function(_v, cellmeta, record){
        return '<div id="fileName_' + record.data.fileId + '">' + _v + '</div>';
    },
    formatIcon : function(_v, cellmeta, record){
        var returnValue = '';
        var extensionName = _v.substring(1);
        var fileId = record.data.fileId;
        if(_v){
            var css = '.db-ft-' + extensionName.toLowerCase() + '-small';
            if(Ext.isEmpty(Ext.util.CSS.getRule(css),true)){ //判断样式是否存在
                returnValue = '<div id="fileType_' + fileId + '" class="db-ft-unknown-small" style="height: 16px;background-repeat: no-repeat;">'
                                  + '&nbsp;&nbsp;&nbsp;&nbsp;' + extensionName.toUpperCase() + '</div>';
            }else{
                returnValue = '<div id="fileType_' + fileId + '" class="db-ft-' + extensionName.toLowerCase() 
                                + '-small" style="height: 16px;background-repeat: no-repeat;"/>&nbsp;&nbsp;&nbsp;&nbsp;' 
                                + extensionName.toUpperCase();    + '</div>';
            }
            return returnValue;    
        }
        return '<div id="fileType_' + fileId + '" class="db-ft-unknown-small" style="height: 16px;background-repeat: no-repeat;"/>&nbsp;&nbsp;&nbsp;&nbsp;' 
                + extensionName.toUpperCase() + '</div>';    
    },
    formatProgressBar : function(_v, cellmeta, record){
        var returnValue = '';
        switch(record.data.fileState){
            case SWFUpload.FILE_STATUS.COMPLETE:
                if(Ext.isIE){
                    returnValue = 
                        '<div class="x-progress-wrap" style="height: 18px">' +
                            '<div class="x-progress-inner">' +
                                '<div style="width: 100%;" class="x-progress-bar x-progress-text">' + '100 %'
                                '</div>' +
                            '</div>' +
                        '</div>';
                }else{
                    returnValue = 
                        '<div class="x-progress-wrap" style="height: 18px">' +
                            '<div class="x-progress-inner">' +
                                '<div id="progressBar_' + record.data.fileId + '" style="width: 100%;" class="x-progress-bar">' +
                                '</div>' +
                                '<div id="progressText_' + record.data.fileId + '" style="width: 100%;" class="x-progress-text x-progress-text-back" />100 %</div>'
                            '</div>' +
                        '</div>';
                }
                break;
            default : 
                returnValue = 
                    '<div class="x-progress-wrap" style="height: 18px">' +
                        '<div class="x-progress-inner">' +
                            '<div id="progressBar_' + record.data.fileId + '" style="width: 0%;" class="x-progress-bar">' +
                            '</div>' +
                            '<div id="progressText_' + record.data.fileId + '" style="width: 100%;" class="x-progress-text x-progress-text-back" />0 %</div>'
                        '</div>' +
                    '</div>';
                break;
        }
        return returnValue;
    },
    formatState : function(_v, cellmeta, record){
        var returnValue = '';
        switch(_v){
            case SWFUpload.FILE_STATUS.QUEUED:
                returnValue = '<span id="' + record.id + '"><div id="fileId_' + record.data.fileId + '" class="ux-cell-icon-delete"></div></span>';
                break;
            case SWFUpload.FILE_STATUS.CANCELLED:
                returnValue = '<span id="' + record.id + '"><div id="fileId_' + record.data.fileId + '" class="ux-cell-icon-clear"></div></span>';
                break;
            case SWFUpload.FILE_STATUS.COMPLETE:
                returnValue = '<span id="' + record.id + '"><div id="fileId_' + record.data.fileId + '" class="ux-cell-icon-completed"></div></span>';
                break;
            default : 
                Alert.warning('状态不正确!');
                break;
        }
        return returnValue;
    },
    onCancelQueue : function(fileId){
        Ext.getDom('fileName_' + fileId).className = 'ux-cell-color-gray';//设置文字颜色为灰色
        Ext.getDom('fileSize_' + fileId).className = 'ux-cell-color-gray';
        Ext.DomHelper.applyStyles('fileType_' + fileId,'font-style:italic;text-decoration: line-through;color:gray');
    },
    onFileQueued : function(file){
        if(file.name.length > 72){
            Alert.warning('文件名称不允许超过72个长度.');
            return;
        }
        var thiz = this.customSettings.scope_handler;
        var _flag = false;
        //阻止上传名称相同的文件
        if(thiz.fileList.getStore().getCount() > 0){
            thiz.fileList.getStore().each(function(record) { 
                if(record.get("fileName") == file.name){
                    _flag = true;
                    return;
                }
            });
        }
        if(_flag){
            Alert.warning('文件名重复!');
            return;
        }
        thiz.fileList.getStore().add(new Eyeson.Components.FileRecord({
            fileId : file.id,
            fileName : file.name,
            fileSize : file.size,
            fileType : file.type,
            fileState : file.filestatus
        }));
        thiz.progressInfo.filesTotal += 1;
        thiz.progressInfo.bytesTotal += file.size;
        thiz.updateProgressInfo();
    },
    onQueueError : function(file, errorCode, message){
        try {
            if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
                Ext.Msg.alert('提示',"你尝试添加太多的文件进入队列.\n" + (message === 0 ? "你已经超出上传限定范围." : "你只可以选择 " + (message > 1 ? "上传 " + message + " 文件." : "一个文件.")));
                return;
            }
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    Ext.Msg.alert('提示',"错误码: 文件太大, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 消息: " + message);
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    Ext.Msg.alert('提示',"错误码: 0 字节文件, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 消息: " + message);
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    Ext.Msg.alert('提示',"错误码: 无效文件类型, 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 消息: " + message);
                    break;
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    Ext.Msg.alert('提示',"你选择文件数量太多.  " +  (message > 1 ? "你只能添加 " +  message + " 更多的文件" : "你不能添加更多的文件."));
                    break;
                default:
                    if (file !== null) {
                    }
                    Ext.Msg.alert('提示',"错误码: " + errorCode + ", 文件名: " + file.name + ", 文件尺寸: " + file.size + ", 消息: " + message);
                    break;
            }
        } catch (ex) {
            Alert.show('产生错误!');
            this.debug(ex);
        }
    },
    onFileDialogComplete : function(selectedFilesCount, queuedFilesCount){
        //alert("selectedFilesCount:" + selectedFilesCount + "  queuedFilesCount:" + queuedFilesCount );//选择文件数量
    },
    onUploadStart : function(file){},
    onUploadProgress : function(file, completeBytes, bytesTotal){
        var percent = Math.ceil((completeBytes / bytesTotal) * 100);
        Ext.getDom('progressBar_' + file.id).style.width = percent + "%";
        Ext.getDom('progressText_' + file.id).innerHTML = percent + " %";
        
        var thiz = this.customSettings.scope_handler;
        var bytes_added = completeBytes - thiz.progressInfo.currentCompleteBytes;
        thiz.progressInfo.bytesUploaded += Math.abs(bytes_added < 0 ? 0 : bytes_added);
        thiz.progressInfo.currentCompleteBytes = completeBytes;
        if (thiz.progressInfo.lastUpdate) {
            thiz.progressInfo.lastElapsed = thiz.progressInfo.lastUpdate.getElapsed();
            thiz.progressInfo.timeElapsed += thiz.progressInfo.lastElapsed;
        }
        thiz.progressInfo.lastBytes = bytes_added;
        thiz.progressInfo.lastUpdate = new Date();
        thiz.updateProgressInfo();
    },
    onUploadError : function(file, errorCode, message){
        var thiz = this.customSettings.scope_handler;
        switch(errorCode){
            case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                thiz.progressInfo.filesTotal -= 1;
                thiz.progressInfo.bytesTotal -= file.size;
                thiz.updateProgressInfo();
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
        }
    },
    onUploadSuccess : function(file, serverData){
        var _jsonData = Ext.util.JSON.decode(serverData);
        var thiz = this.customSettings.scope_handler;
        if(_jsonData.success){
            var record = thiz.fileList.getStore().getById(Ext.getDom('fileId_' + file.id).parentNode.id);
            record.set('fileState',file.filestatus);
            record.commit();
            //上传成功后 文件名称 添加到文件列表
            var fileGridList = this.customSettings.scope_handler.fileGridList;
            if(fileGridList && fileGridList.store){
                this.customSettings.scope_handler.fileGridList.store.add(new Ext.data.Record({
                    fileId : _jsonData.fileId != 0 ? _jsonData.fileId : '',
                    fileName : _jsonData.fileName,
                    filePath : _jsonData.filePath,
                    fileType : _jsonData.fileType
                }));
            }else{
                if(fileGridList.filePaths != null){
                    var file = {
                        fileId : _jsonData.fileId != 0 ? _jsonData.fileId : '',
                        fileName : _jsonData.fileName,
                        filePath : _jsonData.filePath,
                        fileType : _jsonData.fileType
                    }
                    fileGridList.filePaths.push(file);
                }
            }
        }
        thiz.progressInfo.filesUploaded += 1;
        thiz.updateProgressInfo();
    },
    onUploadComplete : function(file){
        if (this.getStats().files_queued > 0 && this.uploadStopped == false) {
            this.startUpload();
        } 
    }
});

Eyeson.Components.FileRecord = Ext.data.Record.create([
    {name : 'fileId'},
      {name : 'fileName'},
      {name : 'fileSize'},
      {name : 'fileType'},
      {name : 'fileState'}
]);
FileUploadDialog
Alert = {
    show : function(msg ,fn , scope){
        Ext.Msg.show({
            title : '提示!',
            msg : msg ,
            buttons : Ext.Msg.OK,
            fn : function(btn){
                if(btn == 'ok' && fn){
                    fn.call(this);
                }
            },
            scope : scope
        });
    },
    info : function(msg){
        Ext.MessageBox.show({
              title : '消息提示!',
            msg : msg,
            width : 200,
            buttons : Ext.Msg.OK,
            icon : Ext.MessageBox.INFO
        });
    },
    warning : function(msg){
        Ext.MessageBox.show({
              title : '警告提醒!',
            msg : msg,
            width : 200,
            buttons : Ext.Msg.OK,
            icon : Ext.MessageBox.WARNING
        });
    },
    error : function(msg){
        Ext.MessageBox.show({
              title : '发生错误!',
            msg : msg,
            width : 200,
            buttons : Ext.Msg.OK,
            icon : Ext.MessageBox.ERROR
        });
    },
    msg : function(msg , color){
        var format = '<span style="font-size: 14px; color: ' + (color || 'green') + ';">' + msg + '</span>';
        var title = '提示!';
        if(!this.msgCt){
            this.msgCt = Ext.DomHelper.insertFirst(document.body, {'class' : 'msg-div'}, true);
        }
        this.msgCt.alignTo(document, 't-t');
        var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
        var m = Ext.DomHelper.append(this.msgCt, {html : this.createBox(title, s)}, true);
        m.slideIn('t').pause(2).ghost('t', {remove : true});
    }
}
Alert
Ext.ns('Eyeson.Common.Util');
/**
 * 工具类
 * @type Eyeson.Common.Util
 * @type Eyeson.Util
 */
Eyeson.Util = Eyeson.Common.Util = {
    getValue : function(o , property){
        var deeps = property.split('.');
        var v = o;
        for (var j = 0; j < deeps.length; j++) {
            var property = deeps[j];
            if(v instanceof Ext.data.Record){
                v = v.get(property);
            }else{
                v = v ? v[property] : '';
            }
        }
        return v;
    },
    setValue : function(o , property , value){
        var deeps = property.split('.');
        var v = o;
        for (var j = 0; j < deeps.length; j++) {
            var property = deeps[j]
            if(v instanceof Ext.data.Record){
                if(deeps.length > 1){
                    var result = v.get(property);
                    if(result == null){
                        result = {};
                        v.set(property , result);
                        v = result;
                    }else{
                        var newObject = {};
                        v.set(property , newObject);
                        Ext.apply(newObject , result);
                        v = newObject;
                    }
                }else{
                    v.set(property , value);
                }
            }else{
                if(v && j == deeps.length - 1){
                    v[property] = value;
                }else{
                    v = v ? v[property] : {};
                }
            }
        }
    },
    getFormURI : function(uri , form , opt){
        var formValues = form.getValues();
        var params = {};
        for (var param in formValues) {
            if (form.findField(param) && 
                form.findField(param).emptyText != formValues[param] && 
                formValues[param] != '') {
                params[param] = formValues[param];
            }
        }
        Ext.apply(params , opt);
        return this.getURI(uri , params);
    },
    getURI : function(uri , params){
        var parameters = [];
        for(var param in params){
            parameters.push(param + "=" + params[param]);
        }
        //
        var fulluri = '';
        if(parameters.length > 0){
            var fulluri = parameters.join("&");
            if(uri.indexOf('?') < 0){
                fulluri = uri + "?" + fulluri;
            }else{
                fulluri = uri + "&" + fulluri;
            }
        }
        return fulluri;
    },
    getUniqueID : function(){
        var date = new Date().dateFormat('YmdHisu');
        return 'id' + date.toString();
    },
    toUnicode : function(text) {
        text = escape(text.toString()).replace(/\+/g, "%2B");
        var matches = text.match(/(%([0-9A-F]{2}))/gi);
        if (matches) {
            for (var matchid = 0; matchid < matches.length; matchid++) { 
                var code = matches[matchid].substring(1,3); 
                if (parseInt(code, 16) >= 128) { 
                    text = text.replace(matches[matchid], '%u00' + code); 
                }
            }
        }
        text = text.replace('%25', '%u0025'); 
        return text; 
    }
};
Util
var dialog = new Eyeson.Components.FileUploadDialog({
       uploadUrl : '../../BsSourceManagerController/toUpload.do', //服务端上传方法
       fileTypes : '*.png;*.jpg;.jpeg',
       params : {
           path : this.path
       }
}); dialog.show();

样式关联的图标文件下载地址:

https://files.cnblogs.com/javalism/iconx.rar

 

(*)步骤二:服务端SpringMVC方法

使用SpringWeb的文件上传对象,此段语句必须要放进spring-context.xml配置文件中(否则无法直接使用MultipartHttpServletRequest对象)。

<!-- Spring初始化时会根据此ID来设置文件上传的Request实现类. -->
<
bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean>
@RequestMapping("/toUpload")
public void toUpload(HttpServletRequest request , String path , HttpServletResponse response) throws Exception{
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    for (MultipartFile file : multipartRequest.getFileMap().values()) {
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        String fullPath = StringUtil.fmt("{0}/{1}{2}", path , UniqueID.toTimes() , suffix);
        FileOutputStream fos = new FileOutputStream(fullPath);
        fos.write(file.getBytes());
        fos.close();
    }
   //这里必须要返回如下对象形式,批量文件传输才会按照队列来进行.. toJSON(
"{}", response); }
public class FileUtil {
    
    public static void remove(String path){
        File file = new File(path);
        file.delete();
    }
    
    public static String getSuffix(String filename) {
        int index = filename.lastIndexOf(".");
        if (index == -1) {
            return filename;
        }
        String suffix = filename.substring(index);
        return suffix;
    }
}
FileUtil
public class StringUtil {
    /**
     * <p>Description: 格式化字符串</p>
     * <p>如: StringUtil.fmt("我是{0}",猪),输出:我是猪</p>
     * @param expression 表达式  
     * @param values  对占位符进行填充替换
     * @return 字符串
     */
    public static String fmt(String expression, Object... values) {
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                if(values[i] != null){
                    expression = expression.replace("{" + i + "}", String.valueOf(values[i]));
                }else{
                    expression = expression.replace("{" + i + "}", "");
                }
            }
            return expression;
        }
        return null;
    }
}
StringUtil

 

最终效果图如下(图中的文字我在项目用了国际化,所以大致差不多就是这样子的):

 

整理完毕,有些地方都是代码片段,我直接从项目中截取的,如果大家有什么疑问可以回复留言!

 

posted on 2013-12-05 13:35  MR.Cary  阅读(1574)  评论(0)    收藏  举报

导航