使用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 ****************************
}



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