Flex之小功能——文件上传(Flex+java)

仿照网上“半杯咖啡”的文章,做了一下FLEX+JAVA的多个文件上传功能

Flex实现多文件上传之一:前台部分

Flex实现多文件上传之二:后台部分(java) 

半杯咖啡写的还是很好的,就是没全公开源码(不过主要代码已经给出了...).有些地方我还没弄懂:如进度条刷新... 效果如下:
 

界面就是仿照“半杯咖啡”的上传界面,加了TOOLTIP,位置没调。大小进行处理了,不过就是进度条没有处理好!删除一条数据时,再加入文件,位置不变的话进度条也不变!试了很多方法,就是没法改变。按照“半杯咖啡”的写法我这就报错,而且没看懂这代码什么意思:grid.parent.refresh();  而且它是在itemrenderer里面,不好处理! 希望有高人指点一二。

 

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="486" height="316" title="文件上传" fontSize="12" borderColor="#CCECB7" backgroundColor="#A0D3B9" backgroundAlpha="0.8" status="此次共上传{selectedFiles.length}个文件">
<mx:Script>
	<![CDATA[
		import mx.MediaVO;
		import mx.core.Application;
		import mx.managers.PopUpManager;
		import mx.collections.ArrayCollection;
		import mx.controls.DataGrid;
		import flash.net.FileReference;
		import mx.rpc.events.ResultEvent;
		import mx.rpc.events.FaultEvent;
		import mx.rpc.events.ResultEvent;
		import mx.controls.Alert;
	
		//声明上传用到的FileReferenceList
		[Bindable]
		private var fileL:FileReferenceList;
		//声明上传文件用到的servlet(其实已经通过show方法传入)
		[Bindable]
		private var uploadUrl:String;
		//选择文件时用到的arrayCollection,也是datagrid的数据源
		[Bindable]
		private var selectedFiles:ArrayCollection = new ArrayCollection;
		
		//谁需要此组件的时候就调用此方法   UploadPanel.show("http://localhost:8082/Myflex/upload");
		public static function show(uploadUrl:String = ""):void
		{
			var parentApp:Application = Application.application as Application;
			var uv:UploadPanel = UploadPanel(PopUpManager.createPopUp(parentApp,UploadPanel,true));
			uv.uploadUrl = uploadUrl;
			PopUpManager.centerPopUp(uv);
		}
		//浏览文件
		private function addFiles():void
		{
			fileL = new FileReferenceList();
			fileL.addEventListener(Event.SELECT,selectFiles);
			fileL.browse();
		}
		//选择文件到列表
		private function selectFiles(event:Event):void
		{
			for(var i:int=0;i<event.currentTarget.fileList.length;i++){
			   var f:FileReference = FileReference(event.currentTarget.fileList[i]); 
			   //obj是为了在datagird中显示将要上传的文件信息
			   var obj:Object= new Object();
			   obj.fileName = f.name;
			   obj.fileSize = formatFileSize(f.size);
			   obj.fileType = f.type;
			   obj.fileRefrence = f;
			   selectedFiles.addItem(obj);
			}
		}
		//逐个上传文件
		private function uploadHandler():void{
			var file:FileReference;
			for(var i:int = 0 ;i<selectedFiles.length;i++){
		   		file = FileReference(selectedFiles[i].fileRefrence);
		   		//media是将数据保存到数据库中声明的对象,不保存信息的话,这一段可以不要
		   		var media:MediaVO = new MediaVO();
		   		media.testid = this.parentApplication.tid;
		   		media.mc = file.name;
		   		media.size = formatFileSize(file.size);
		   		media.attachment = "D:\\upload\\"+file.name;
		  		this.parentApplication.aom2.mediaSvc.save(media);//由于remoteObject在别的窗口中,此句不必深究....
		  		
		   		file.upload(new URLRequest(uploadUrl));
			}
		}
		
		// 格式化文件大小
		private function formatFileSize(numSize:Number):String {
			var strReturn:String;
			numSize = Number(numSize / 1000);
			strReturn = String(numSize.toFixed(1) + " KB");
			if (numSize > 1000) {
				numSize = numSize / 1000;
				strReturn = String(numSize.toFixed(1) + " MB");
				if (numSize > 1000) {
					numSize = numSize / 1000;
					strReturn = String(numSize.toFixed(1) + " GB");
				}
			}				
			return strReturn;
		}
		//关闭本窗口
		private function close():void
		{
			PopUpManager.removePopUp(this);
		}
	]]>
</mx:Script>

	<mx:DataGrid id="dg" dataProvider="{selectedFiles}" y="33" width="446" height="184" fontSize="10" horizontalCenter="0" textAlign="center" fontFamily="Verdana">
		<mx:columns>
			<mx:DataGridColumn headerText="文件名称" dataField="fileName" width="120" showDataTips="true"/>
			<mx:DataGridColumn headerText="文件大小" dataField="fileSize" width="60"/>
			<mx:DataGridColumn headerText="文件类型" dataField="fileType" width="50"/>
			<mx:DataGridColumn headerText="上传状态" width="130">
				<mx:itemRenderer>
				  <mx:Component>
				    <mx:HBox width="130" horizontalGap="2">
				     <mx:ProgressBar id="progress" width="100" 
				      minimum="0" maximum="100" source="{data.fileRefrence}" 
				      labelPlacement="center" progress="progress.label='%3%%';"
				      label="%3%%"
				      paddingLeft="2"
				      paddingRight="2">
				     </mx:ProgressBar>
				     <mx:LinkButton width="15" toolTip="取消上传" click="cancel()"
				      icon="@Embed('assets/cancel.png')"  paddingLeft="2">
				      <mx:Script>
					       <![CDATA[
					        private function cancel():void{
					         data.fileRefrence.cancel();
					         progress.label = "已取消";
					        }
					       ]]>
					  </mx:Script>
				     </mx:LinkButton>
				     <mx:LinkButton width="15" click="deleteItem(event)" 
				      icon="@Embed('assets/delete.png')" toolTip="从列表中删除" paddingLeft="2">
				     	<mx:Script>
					       <![CDATA[
					        import mx.collections.ArrayCollection;
					        import mx.controls.DataGrid;
					       
					        private function deleteItem(event:MouseEvent):void {
					         var grid:Object = event.target.parent.parent.parent;
					         var dp:ArrayCollection = ArrayCollection(grid.dataProvider);
					         var index:int = dp.getItemIndex(data);
					         dp.removeItemAt(index); 
					         progress.label = "0%";//刷新进度条的label
					         //grid.parent.refresh();	//这句在我机子上报错!哎...				        }
					       ]]>
					      </mx:Script>
				     </mx:LinkButton>
				    </mx:HBox>
				  </mx:Component>
				</mx:itemRenderer>
			</mx:DataGridColumn>
		</mx:columns>
	</mx:DataGrid>
	<mx:Button x="199" y="233" label="浏览..." click="addFiles()"/>
	<mx:Button x="289" y="233" label="上传" width="64" enabled="{selectedFiles.length>0}" click="uploadHandler()"/>
	<mx:Button x="379" y="233" label="关闭" width="64" click="close()"/>
  </mx:Panel>

 相应的servlet代码如下:

package yang.utils;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.util.List;
import org.apache.commons.fileupload.FileUploadException;
import java.util.Iterator;
import org.apache.commons.fileupload.FileItem;
import java.io.File;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.ObjectUtils;

public class FileUploadAction extends HttpServlet{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(FileUploadAction.class.getName());

    private int maxPostSize = 100 * 1024 * 1024;
    private String uploadPath = "D:\\upload\\";


    public FileUploadAction() {
    }

    //文件上传
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
        logger("begin upload");
        try {
    request.setCharacterEncoding("UTF-8");//防止文件名称带有汉字后传到服务器乱码
   } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
        response.setContentType("text/html; charset=UTF-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 4);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(maxPostSize);

        logger("request================"+ObjectUtils.toString(request));
        List fileItems = null;
        try {
            fileItems = upload.parseRequest(request);
            logger("===================="+ObjectUtils.toString(fileItems));
            Iterator iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                log(item.toString());
                if (!item.isFormField()) {
                    String name = item.getName();
                    logger("file name = "+name);
                    try {
                        item.write(new File(uploadPath + name));
                    }
                    catch (Exception ex) {
                        logger(ex.getMessage());
                    }
                }
            }
        }
        catch (FileUploadException ex1) {
            logger("FileUploadException->"+ex1.getMessage());
        }


    }

    private void logger(String info){
        System.out.println(info);
    }

}

 

不过不要忘了在web.xml中加入:

<!-- For file uploaded -->  
   <servlet>  
        <servlet-name>FileUploaded</servlet-name>  
        <servlet-class>yang.utils.FileUploadAction</servlet-class>  
    </servlet>  
  
    <servlet-mapping>  
        <servlet-name>FileUploaded</servlet-name>  
        <url-pattern>/FileUploaded</url-pattern>  
    </servlet-mapping>

 

 

此处有两个上传组件可以参考:

 

http://labs.newmediateam.com/Multifileupload/FileUpload.html

 

http://weblog.cahlan.com/files/FileUpload/FileUploadApp.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值