自己封装的Flex文件上传组件FileInput

本文介绍了一个自定义的Flash文件上传组件,该组件简化了文件上传流程,并提供了文件大小限制及类型过滤功能。同时,还展示了如何使用Struts2进行文件接收及处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目里面文件上传用得比较平凡,因而自己封装了一个简单的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 + " 大小超过限制了! \n";
					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>



Demo代码如下:

<?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 + struts2后台代码:
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;
	}
	
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值