`
softlife
  • 浏览: 106431 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ext2.2+struts2.0上传进度条

阅读更多
第一步:js部分代码

var fp = new Ext.FormPanel({
	fileUpload : true,
	width : 400,
	frame : true,
	title : '上传图片',
	autoHeight : true,
	bodyStyle : 'padding: 10px 10px 0 10px;',
	labelWidth : 50,
	url : 'uploadController?t=' + new Date(),
	defaults : {
		anchor : '95%',
		allowBlank : false,
		msgTarget : 'side'
	},
	items : [{
				xtype : 'textfield',
				fieldLabel : '名称',
				name : 'name',
				invalidText : '必须填写图片名称'
			}, {
				xtype : 'fileuploadfield',//此控件使用extjs的api中FileUploadField.js
				id : 'form-file',
				emptyText : '选择图片...',
				invalidText : '必须选择图片',
				fieldLabel : '地址',
				name : 'url',
				buttonCfg : {
					text : '',
					iconCls : 'upload'
				}
			}],
	buttons : [{
		text : 'Save',
		handler : function() {
			if (fp.getForm().isValid()) {
				//显示进度条
				Ext.MessageBox.show({
							title : '正在上传文件',
							width : 280,
							progress : true,
							icon : Ext.MessageBox.INFO,
							cls : 'custom',//配置在css中图片
							closable : false
						});
				fp.getForm().submit({
							method : 'POST',
							success : function(form, action) {
								alert(action.result);
							}
						});
				//设置一个定时器,每500毫秒向processController发送一次ajax请求
				var timer = setInterval(function() {
					//请求事例
					Ext.Ajax.request({
															//最好在ajax的请求的url上面都要带上日期戳,
								//否则有可能每次出现的数据都是一样的,
								//这和浏览器缓存有关
								url : 'processController?t=' + new Date(),
								method : 'get',
								//处理ajax的返回数据
								success : function(response, options) {
									var obj = Ext.util.JSON
											.decode(response.responseText);
									if (obj.success != false) {
										if (obj.finished) {
											clearInterval(timer);
											Ext.MessageBox.updateProgress(1,
													obj.msg, 'finished');
											Ext.MessageBox.hide();
										} else {
											var percentage = obj.percentage;
											var process = percentage
													.toString()
													.substr(0, 6)
													.replace(
															/^(\d+\.\d{2})\d*$/,
															"$1");
											if (process > 1) {
												return;
											}
											//1.var number = 123.4567   
											//number.toString().replace(/^(\d+\.\d{2})\d*$/,"$1") //结果:123.45  
											//2.var number = 123.4567  
											//number.toFixed(2); //结果:123.46 //IE 5.5以上 
											Ext.MessageBox.updateProgress(
													percentage, process * 100
															+ "%");
										}
									}
								},
								failure : function() {
									clearInterval(timer);
									Ext.Msg.alert('错误', '发生错误了。');
								}
							});
				}, 500);
			}
		}
	}, {
		text : 'Reset',
		handler : function() {
			fp.getForm().reset();
		}
	}]
});

第二步:java类实现
package com.test.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.myaction.FrmAction;//此frmaction是自封装类,此类实现了struts2.0的基本接口
import com.davidjc.ajaxfileupload.multipart.ProgressMonitor;
/**
 * 主页图片面板控制action
 *
 */
public class ImageAction extends FrmAction {
	
	private File url;
	private String fileName;
	private String contentType;
	
	public File getUrl() {
		return url;
	}
	public void setUrl(File url) {
		this.url = url;
	}
	public void setUrlFileName(String fileName) {
		this.fileName = fileName;
	}
	public void setUrlContentType(String contentType) {
		this.contentType = contentType;
	}
	/**
	 * 上传文件
	 * @param src
	 * @param dst
	 */
	private  void copy(File src, File dst)  {
        try  {
           InputStream in = null ;
           OutputStream out = null ;
            try  {                
               in = new BufferedInputStream( new FileInputStream(src) );
               out = new BufferedOutputStream( new FileOutputStream(dst));
               byte [] buffer = new byte [in.available()];
               while (in.read(buffer) > 0 )  {
                  out.write(buffer);
              }                
            } finally  {
                if ( null != in)  {
                   in.close();
               } 
                 if ( null != out)  {
                   out.close();
               } 
           } 
        } catch (Exception e)  {
        	
           e.printStackTrace();
       } 
   }
	/**
	 * 上传控制文件
	 * @return
	 */
	public String uploadController(){
		try {
			String imageName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
	        File uploadedFile = new File(request.getSession().getServletContext().getRealPath( "/images" ) + "/" + imageName);
	        copy(url, uploadedFile);
	        response.getWriter().write("{success:true,msg:'上传文件成功!'}");
			response.getWriter().flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}
	/**
	 * 上传进程控制
	 * @return
	 * @throws Exception 
	 */
	public String processController() throws Exception{
		
		double d = 0.00;
		//从session取出uploadPercentage并送回浏览器
		Object mon_obj = this.sessionMap.get("com.davidjc.ajaxfileupload.multipart.ProgressMonitor");
		   if (mon_obj != null) {
		      ProgressMonitor monitor = (ProgressMonitor)mon_obj;
		      d = ((double)monitor.getBytesRead()/(double)monitor.getBytesLength());
		  }
	   
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+d+"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
	    String msg = "";
	    if(d<1){
	    //d<0代表正在上传,
	        msg = "正在上传文件...";
	        response.getWriter().write("{success:true, msg: '"+msg+"', percentage:'" + d + "', finished: false}");
	    }
	    else if(d>=1){
	        //d>1 代表上传已经结束
	        msg = "上传成功!";
	        this.sessionMap.remove("com.davidjc.ajaxfileupload.multipart.ProgressMonitor");
	        
	        response.getWriter().write("{success:true, msg: '"+msg+"', percentage:1, finished:true}");
	        //注意返回的数据,success代表状态
	        //percentage是百分比
	        //finished代表整个过程是否结束。
	    }
	    response.getWriter().flush();

		return NONE;
	}

}

第三步:在struts.xml加入如下配置

<!--实现机制:使用我们自己的解析器,主要机上 progressListener; -->
<bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest" name="monitoredJakarta" 
	class="com.davidjc.ajaxfileupload.multipart.MonitoredMultiPartRequest" scope="default" optional="true" /> 
	<constant name="struts.multipart.parser" value="monitoredJakarta"/> 
    <constant name="struts.multipart.maxSize" value="2000000000"/><!--解决不能上传大于2M文件问题-->



主要依赖jar文件:
commons-io-1.3.1.jar
commons-fileupload-1.2.jar
AjaxFileUpload-0.03.jar //此jar文件自定义实现上传机制。载入附件中。

注:此文章是本人把网上七零八碎的资料整理后的结果。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics