使用Extjs Struts2 实现文件的上传功能

                     文件上传在平时的应用开发中是非常常见的,今天总结一下使用Extjs和Struts 来实现单个文件的简单上传,今天就以图片的上传为例子写个小的demo。

图片上传后效果:

                                        

前台的js文件代码:

Ext.onReady(function(){
	Ext.create('Ext.form.Panel', {
	    title: 'Upload a Photo',
	    width: 400,
	    bodyPadding: 10,
	    frame: true,
	    renderTo: Ext.getBody(),
	    items: [{
	        xtype: 'filefield',
	        id :'file',
	        name: 'photo',     //  设置文件上传的name
	        fieldLabel: 'Photo',
	        labelWidth: 50,
	        msgTarget: 'side',
	        allowBlank: false,
	        anchor: '100%',
	        buttonText: 'Select Photo...',
	        listeners:{               // 配置当选中文件发生改变时
	        	 'change':function(file,oldFile,newFile){
	        		// 在这里可以得到文件的实际物理路劲,达到预览的效果,今天没有调试出来,改天继续???预留
//	 	        	alert(file);  // 得到本地文件
//	 	        	alert(fileName);       // 得到文件名
//	 	        	alert(object);
//	        		 Ext.getCmp('theimage').getEl().dom.src ='images/14-07-25.jpg';
	 		    }
		    }
	       
	    },{
//	    	 columnWidth: 18,
             bodyStyle: ' margin:4px 10px 10px 5px',
             layout: 'form',
             id:'form1',
             items: [{
                 	xtype: 'box',
                 	id: 'theimage',
                     width: 400, height: 150,
                     //html:'<img id="xxx" src=""/>',
                     autoEl: {          //  用来显示上传的图片
                  	   tag: 'img',    //指定为img标签    
                  	   src: '' ,   //指定url路径    ,
                  	}
            	 
                 }
                 

             ]
	    	
	    }],
	    buttons: [{
	        text: 'Upload',
	        handler: function() {
	            var form = this.up('form').getForm();
	            if(form.isValid()){
	                form.submit({
	                    url: 'fileUploadAction',
	                    waitMsg: 'Uploading your photo...',
	                    success: function(fp, o) {
	                        Ext.Msg.alert('Success', 'Your photo "' + o.result.fileName + '" has been uploaded.');
	                        Ext.getCmp('theimage').getEl().dom.src ='images/'+o.result.fileName;
	                    }
	                });
	            }
	        }
	    }]
});

	
});
FileUploadAction  代码:
package edu.hue.jk.action;
import java.io.File;

@Controller("fileUploadAction")
public class FileUploadAction extends ActionSupport {
	private File photo;    //对应上传的js上传文件的属性:   name: 'photo',     //  设置文件上传的name  
	private JSONObject result;
	private String photoFileName;  // 对应上传的文件名
	private String photoContentType; // 对应上传的文件类型
	//得到文件实际存储的名字
	public String getRealStoreName(){
		int hzPostion=photoFileName.lastIndexOf('.');    // 得到最后一个点的下标
		String houZui=photoFileName.substring(hzPostion,photoFileName.length());
		Date theDate=new Date();// 取当前日期
		SimpleDateFormat dateFormat=new SimpleDateFormat("yy-MM-dd");
		return dateFormat.format(theDate)+houZui;        //  根据当前的日期重新命名  ,这个应该是根据实际需要可以根据时间来命名
	}
	// 得到文件的真实存储路径
	public String getRealPath(){
		ServletContext context=ServletActionContext.getServletContext();
		
		System.out.println("图片的物理路径为:"+photo.getAbsolutePath());
		return context.getRealPath("/images")+"\\"+ getRealStoreName();
	}
	// 将源路劲的文件复制到目的路劲的文件
	boolean copyFile(File src ,File dist){
		boolean isCopy =true;
		FileInputStream in=null;
		FileOutputStream out=null;
		try {
			in=new FileInputStream(src);
			out=new FileOutputStream(dist);
			byte[] buff=new byte[1024];
			int length=0;  // 每次复制的字节数
			while((length=in.read(buff, 0, 1024))>0){
				out.write(buff, 0, length);
			}
		} catch (Exception e) {
			isCopy=false;              //  文件复制失败
			e.printStackTrace();
		}
		return isCopy;
		
	}
	/***
	 * 用来处理文件的复制,实质上还是一个文件的读写
	 */
	@Override
	public String execute() throws Exception {// 后台打印上传文件的信息
//		System.out.println("fileContentType:"+photoContentType);
//		System.out.println("fileName:"+photoFileName);
		System.out.println("filePath:"+photo.getAbsoluteFile().getPath());
//		System.out.println("fileRealPath:"+getRealPath());
		Map<String,Object> map=new HashMap<String,Object>();
		if(copyFile(photo,new File(getRealPath())))
		{
			map.put("success",true);
			map.put("fileName", getRealStoreName());
		}
		else
			map.put("success",false);
		
		result=JSONObject.fromObject(map);
		return super.execute();
	}
	//******************* setter  and getter start****************************
	public String getPhotoFileName() {
		return photoFileName;
	}
	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}
	public String getPhotoContentType() {
		return photoContentType;
	}
	public void setPhotoContentType(String photoContentType) {
		this.photoContentType = photoContentType;
	}
	public JSONObject getResult() {
		return result;
	}
	public void setResult(JSONObject result) {
		this.result = result;
	}
	public File getPhoto() {
		return photo;
	}
	public void setPhoto(File photo) {
		this.photo = photo;
	}
	//******************* end fo setter  and getter ****************************
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章