패 키 징 된 Flex 파일 업로드 구성 요소 FileInput

최근 프로젝트 에 서 는 파일 업로드 가 평범 하기 때문에 개발 에 편리 하도록 간단 한 FileInput 구성 요 소 를 패키지 했다.잔말 말고 코드 를 입력 하 세 요.
<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="280" height="30">
	<mx:Metadata>
		[Event(name="uploadComplete",type="flash.events.Event")]
		[Event(name="uploadIoError",type="flash.events.IOErrorEvent")]
		[Event(name="uploadSecurityError",type="flash.events.SecurityErrorEvent")]
	</mx:Metadata>
	<mx:Script>
		<![CDATA[
		
			import mx.controls.Alert;
			import flash.net.FileReference;
			import flash.net.URLVariables;
			import flash.net.URLRequestMethod;
			import flash.net.URLRequest;
			
			private var _url:String;
			private var _allowMaxSize:uint = 104857600;
			
			private var _fileRef:FileReference;
			private var _filter:Array;
			private var _sendVars:URLVariables = new URLVariables();
			
			public function set url(uploadUrl:String):void{
				_url = uploadUrl;
			}
			
			public function set allowMaxSize(maxSize:uint):void{
				_allowMaxSize = maxSize;
			}
			
			public function set filter(array:Array):void{
				_filter = array;
			}
			
			public function set sendVars(Vars:URLVariables):void{
				_sendVars = Vars;
			}
			
			private function browse():void{
				Security.allowDomain("*");
				_fileRef = new FileReference();
				_fileRef.addEventListener(Event.SELECT,onSelect);
				_fileRef.browse(_filter);
			}
			
			private function onSelect(evt:Event):void{
				if(checkSize(_fileRef.size)){
					fileName.text = _fileRef.name;
				}else{
					var msg:String = "";
					msg = _fileRef.name + "        ! 
"; Alert.okLabel = ' '; Alert.show(msg + " :" + formatFileSize(_allowMaxSize),' ',Alert.OK).clipContent; } } public function StartUpload():void{ _fileRef.addEventListener(Event.COMPLETE, onComplete); _fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIoError); _fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError); var request:URLRequest = new URLRequest(); request.data = _sendVars; request.url = _url; request.method = URLRequestMethod.POST; // _fileRef.upload(request,'file',false); _fileRef.upload(request); } private function onComplete(event:Event):void { this.dispatchEvent(new Event("uploadComplete")); } private function onIoError(evt:IOErrorEvent):void{ var event:IOErrorEvent = new IOErrorEvent("uploadIoError", false, false, evt.text); this.dispatchEvent(event); } private function onSecurityError(evt:SecurityErrorEvent):void{ var event:SecurityErrorEvent = new SecurityErrorEvent("uploadSecurityError", false, false, evt.text); this.dispatchEvent(event); } // private function checkSize(size:Number):Boolean{ if(size > _allowMaxSize){ return false; } return true; } private function formatFileSize(size:Number):String{ if((1024 * 1024 * 1024) <= size){ return Math.round(size /(1024 * 1024 * 1024)) + "GB"; }else if((1024 * 1024) <= size){ return Math.round(size /(1024 * 1024)) + "MB"; }else if(1024 <= size){ return Math.round(size /1024) + "KB"; }else{ return size + "B"; } } ]]> </mx:Script> <mx:Canvas width="100%" height="100%" fontSize="12"> <mx:TextInput x="3" y="3" width="201" id="fileName" editable="false"/> <mx:Button x="206" y="3" label=" " id="browseBtn" click="browse()" icon="@Embed('/assets/add.png')"/> </mx:Canvas> </mx:Module>

데모 코드 는 다음 과 같 습 니 다.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" fontSize="12" xmlns:ux="com.flex.ux.*">
	<mx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			import flash.net.FileFilter;
			
			public function onComplete():void{
				Alert.show('    !','  ');
			}
			
			public function doIoError():void{
				Alert.show('    !','  ');
			}
			
			public function onSecurityError():void{
				Alert.show('          !','  ');
			}
			
			private var imageTypes:FileFilter = new FileFilter("Images (*.jpg; *.jpeg; *.gif; *.png)", "*.jpg; *.jpeg; *.gif; *.png");
			private var documentTypes:FileFilter = new FileFilter("Documents (*.pdf)",("*.pdf"));
			private var array:Array = new Array(imageTypes,documentTypes);
		]]>
	</mx:Script>
	<mx:Panel width="400" height="200" layout="absolute" horizontalCenter="0" verticalCenter="0" title="      Demo">
		<mx:Canvas x="0" y="0" width="100%" height="100%">
			<ux:FileInput x="44" y="23" id="fileInput" uploadSecurityError="onSecurityError()" uploadIoError="doIoError()" uploadComplete="onComplete()" url="http://localhost:8080/TEST/upload/UploadAction!upload.action"/>
			<ux:FileInput x="44" y="53" id="imgInput" filter="{array}" uploadSecurityError="onSecurityError()" uploadIoError="doIoError()" uploadComplete="onComplete()" url="http://localhost:8080/TEST/upload/UploadAction!upload.action"/>
			<mx:Button x="49" y="109" label="  1" click="{fileInput.StartUpload();}"/>
			<mx:Button x="159.5" y="109" label="  2" click="{imgInput.StartUpload();}"/>
		</mx:Canvas>
			
	</mx:Panel>
	
</mx:Application>


java + struts 2 배경 코드: UploadUtil
package com.io.fileupload;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class UploadUtil {
	/**
	 * 
	 * @param fileName
	 * @return fileName
	 *                
	 * 
	 */
	public static String generateFileName(String fileName) {
		DateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		String formatDate = df.format(new Date());
		int rand = new Random().nextInt(10000);
		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);
		return formatDate + rand + extension;
	}
}


 
/**
 * 
 */
package com.io.fileupload;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.ajax.base.action.BaseAction;

/**
 * @author     2010-3-22
 *
 */
@SuppressWarnings("serial")
public class UploadAction extends BaseAction {
	private File Filedata;
	private String contentType;
	private String filename;
	
	@SuppressWarnings("deprecation")
	public String upload() throws Exception{
		String realPath = ServletActionContext.getRequest().getRealPath("/upload");
		String tname = UploadUtil.generateFileName(this.filename);
//		String tdir = realPath + "\\" + tname;
/*		long s = this.Filedata.length();
		String size = "";
		if((1024 * 1024 * 1024) <= s){
			size = s /(1024 * 1024 * 1024) + "GB";
		}else if((1024 * 1024) <= s){
			size = s /(1024 * 1024) + "MB";
		}else if(1024 <= s){
			size = s /1024 + "KB";
		}else{
			size = s + "B";
		}*/
		File targetfile = new File(realPath, tname);
		FileUtils.copyFile(Filedata, targetfile);
		this.ajaxResponse.setAjaxResponse("    ");
		return "ajax_response";
	}
	
	public File getFiledata() {
		return Filedata;
	}
	public void setFiledata(File filedata) {
		Filedata = filedata;
	}
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public void setFiledataFilename(String filename) {
		this.filename = filename;
	}
	public void setFiledataContentType(String contentType) {
		this.contentType = contentType;
	}
	
}



좋은 웹페이지 즐겨찾기