`
htj1231825
  • 浏览: 39872 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

flex4+servlet批量上传

阅读更多
最近刚刚学习flex4 做了一个批量上传,也不知道这个是不是真正意义上的批量上传。
在这里记录一下,以后有时间再详细改进。

UploadServlet
package upload;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author crystal
 */
public class UploadServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    // 定义文件的上传路径


// 限制文件的上传大小

    private int maxPostSize = 100 * 1024 * 1024;

    public UploadServlet() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("Access !");
        response.setContentType("text/html;charset=UTF-8");

//保存文件到服务器中
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        try {
            List fileItems = upload.parseRequest(request);
            Iterator iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String name = item.getName();
                    System.out.println(name);
                    try {
                    	String ext=name.substring(name.lastIndexOf(".")+1);
                    	String s = UUID.randomUUID().toString().replaceAll("-", "");
                    	String fileName =s+ "."+ext;
                    	
                        item.write(new File(extracted(request)+"flv\\"+ fileName));
                       // SaveFile s = new SaveFile();

                       // s.saveFile(name);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            System.out.println(e.getMessage() + "结束");
        }
    }

	private String extracted(HttpServletRequest request) {
		return request.getRealPath("/");
	}

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>

}


FileUpload.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" fontSize="12" creationComplete="init()" currentState="selected">
	<s:states>
		<s:State name="selected"/>
		<s:State name="upload"/>
		<s:State name="finsh"/>
	</s:states>
	<fx:Declarations>
		<s:RemoteObject id="uploadid" destination="uploadid" /> 
	</fx:Declarations>
	<fx:Script>  
		<![CDATA[ 
			import flash.events.*;
			
			import mx.collections.ArrayList;
			import mx.core.FlexGlobals;
			
			import upl.CustomFileReferenceList;
			import upl.FileReferenceListExample;
			private var files : FileReferenceList;
			[Bindable]
			private var fileArray : ArrayList= new ArrayList();
			private var serverUrl : String;
			private var userId : String;
			private var allowTypes : XML;
			private var fld:CustomFileReferenceList;
			private var   fff:FileReferenceListExample;
			private function init() : void {
				Security.allowDomain("*");
				var params : Object = FlexGlobals.topLevelApplication.parameters;
				serverUrl = encodeURI(parameters.serverUrl);
				userId = params.userId;
				fld=new CustomFileReferenceList();
				fld.addEventListener(Event.SELECT, showSelect);
				new FileReferenceListExample(fld,finsh);
			}
			private function finsh(e:Event):void{
				currentState="finsh";
				fileArray = new ArrayList();
			}
			private function upload() : void {
				fld.browse();
			}    
			private function showSelect(e:Event):void{
				for(var i:int = 0; i < fld.fileList.length; i++) {
					fileArray.addItem(fld.fileList[i]);
				}
			
			}
			private function onSelect(e:Event) : void {
				//fileArray = new ArrayList(files.fileList);
				for(var i:int = 0; i < fileArray.length; i++) {
					var file:FileReference = fileArray.source[i] as FileReference;
					var request: URLRequest = new URLRequest("http://localhost:8080/wb/UploadServlet")
					file.upload(request);
					//uploadid.uploadid(file.data,file.name); 
				}
				currentState='upload'
			}

			protected function button1_clickHandler(event:MouseEvent):void
			{
			currentState="selected";
			fileArray = new ArrayList();
			}

		]]>  
	</fx:Script>  
	
	<s:VGroup width="577" height="363">
		<s:Button label="选择文件" click="upload();"  includeIn="selected"/>
		<s:List height="114" dataProvider="{fileArray}" itemRenderer="FileShow" includeIn="selected"/>
		<s:List dataProvider="{fileArray}" itemRenderer="FileItem" borderVisible="false" includeIn="upload"/>
		<s:Button includeIn="selected"  click="onSelect(event)" label="上传文件"/>
		<s:Button  includeIn="finsh" label="返回" click="button1_clickHandler(event)"/>
	</s:VGroup>
</s:Application>



FileItem.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009" 
				xmlns:s="library://ns.adobe.com/flex/spark" 
				xmlns:mx="library://ns.adobe.com/flex/mx" >
	
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			private var _data:Object;
			override public function set data( obj : Object ) : void { 
				this._data = obj; 
				var file : FileReference = (this._data as FileReference);
				file.addEventListener(ProgressEvent.PROGRESS, onProgress); 
				file.addEventListener(Event.COMPLETE, onComplete);
				fileName.text = file.name;
			}
			
			override public function get data() : Object { 
				return this._data; 
			}
			
			private function onProgress(e:ProgressEvent) : void {
				cancelBtn.visible = true;
				var loaded : uint = e.bytesLoaded / 1024;
				var total : uint =  e.bytesTotal / 1024;  
				var proc:uint = e.bytesLoaded / e.bytesTotal * 100;    
				bar.setProgress(proc, 100);
				bar.label = proc + "%";
				labelProgress.text = loaded + "kb / " + total + "kb";
			}
			
			private function onComplete(e:Event) : void {
				cancelBtn.visible = false;
				//ExternalInterface.call("onUploadComplete");
			}
			
			private function cancelUpload(e:Event) : void {
				var file : FileReference = (this._data as FileReference);
				file.cancel();
			}
		]]>
	</fx:Script>
	<s:layout>
		<s:VerticalLayout/>
	</s:layout>
	<s:HGroup verticalAlign="middle" paddingTop="5" paddingBottom="5">
		<s:Label id="fileName"/>
		<mx:ProgressBar id="bar"    
						labelPlacement="center"    
						minimum="0"    
						visible="true"    
						maximum="100"    
						label="0%"    
						direction="right"    
						mode="manual"    
						width="200"/>
		<s:Label id="labelProgress" />
		<s:Button id="cancelBtn" label="取消" click="cancelUpload(event)" visible="false" />
	</s:HGroup>
</s:ItemRenderer>





FileShow.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009" 
				xmlns:s="library://ns.adobe.com/flex/spark" 
				xmlns:mx="library://ns.adobe.com/flex/mx" >
	<s:layout>
		<s:BasicLayout/>
	</s:layout>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			private var _data:Object;
			override public function set data( obj : Object ) : void { 
				this._data = obj; 
				var file : FileReference = (this._data as FileReference);
				fileName.text = file.name;
			}
			override public function get data() : Object { 
				return this._data; 
			}
		]]>
	</fx:Script>
	<s:HGroup verticalAlign="middle" paddingTop="5" paddingBottom="5">
		<s:Label id="fileName"/>
	</s:HGroup>
</s:ItemRenderer>
  • wb.rar (5.3 MB)
  • 下载次数: 74
0
0
分享到:
评论

相关推荐

    Flex4.6+java+servlet上传图片例子+图片上传预览

    这个"Flex4.6+java+servlet上传图片例子+图片上传预览"的项目,结合了前端的Flex技术和后端的Java Servlet,为我们提供了一个完整的解决方案。下面将详细解释这个项目的各个组成部分及其工作原理。 首先,让我们来...

    Flex+Java Servlet处理文件上传

    Flex+Java Servlet处理文件上传 关于上传文件

    Flex+Java、PHP 批量上传实例文档

    Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、...

    Flex++ & Bison++ for windows

    Flex++ 和 Bison++ 是两个强大的工具,主要用于在编程领域创建解析器和词法分析器,尤其在构建编译器和解释器时非常有用。这两个工具的Windows版本使得开发者能够在Windows平台上进行类似的工作,而无需依赖于Unix或...

    flex+servlet简单实例

    4. **数据交换**:在Flex客户端与Servlet之间,可以通过Flex的HTTPService或WebService组件发起HTTP请求。这些组件可以发送XML或AMF数据,并接收来自Servlet的响应。 5. **Servlet处理逻辑**:Servlet接收到请求后...

    flex4+spring+blazeds整合技术

    《Flex4+Spring+BlazeDS整合技术详解》 在当今的Web开发中,富互联网应用程序(Rich Internet Applications,简称RIA)已经成为一种趋势,而Flex作为Adobe提供的RIA开发框架,结合Spring的优秀企业级服务管理和...

    Flex4+J2EE+Blazeds配置jspweb工程

    Flex4、J2EE和Blazeds是构建富互联网应用程序(RIA)的组合技术,用于创建交互性强、用户体验丰富的Web应用。在这个配置过程中,我们将深入理解这三个组件的作用以及如何将它们整合到一个JSP Web工程中。 1. Flex4...

    Flex+Java Servlet文件上传实例

    【标题】"Flex+Java Servlet文件上传实例"指的是一个结合了Adobe Flex前端技术和Java Servlet后端技术的文件上传系统。Flex是一种基于ActionScript和Flash Player的开放源代码框架,用于构建富互联网应用程序(RIA)...

    flex + servlet 多文件上传

    本示例主要涉及了`Flex`和`Servlet`技术的结合,用于实现多文件上传的功能。`Flex`是一种基于Adobe Flash Player或Adobe AIR运行时的富互联网应用程序(RIA)开发框架,而`Servlet`则是Java Web开发中的服务器端组件...

    MyEclipse7.5+flex4+spring3.0.5+struts2.2.1+hibernate3.6.0+blazeds4.0.0.14931完美整合方案

    本方案提供了一种集成化的开发环境,即"MyEclipse7.5+flex4+spring3.0.5+struts2.2.1+hibernate3.6.0+blazeds4.0.0.14931完美整合方案",它将多个流行的技术框架整合在一起,为Web应用程序开发提供了一个强大的平台...

    Flex+servlet增删改查附带视频.rar

    Flex+servlet增删改查附带视频,视频很详细。从建工程开始到完成增加工能、

    .net+flex批量上传实例demo

    在.NET和Flex技术结合下,批量上传功能是一个常见的需求,特别是在大数据时代,用户可能需要一次性上传多个文件。这个".net+flex批量上传实例demo"提供了一个解决方案,它可以帮助开发者实现高效且用户友好的批量...

    Flex+Java Servlet处理文件上传.doc

    Flex+Java Servlet处理文件上传

    Flex+php 批量上传源码 (可刷新进度条 )

    Flex和PHP结合实现批量上传文件是一项常见的Web开发任务,它涉及到客户端与服务器端的交互以及文件上传进度的实时反馈。本教程将详细讲解如何利用Flex作为前端界面,PHP作为后端处理,创建一个支持批量上传并能刷新...

    Flex+Servlet断点续传Demo

    综上所述,Flex+Servlet断点续传Demo涉及了客户端和服务端的交互、文件分块、状态管理、错误处理等多个方面,通过这个Demo,开发者可以学习到如何在实际项目中实现高效、可靠的文件上传功能。在压缩包中的"upload...

    Flex+Java 文件上传

    在本文中,我们将深入探讨如何实现Flex与Java Servlet结合进行文件上传。首先,我们需要了解Flex是一种基于Adobe AIR的开源框架,用于构建富互联网应用程序(RIA),而Java Servlet是Java平台上的一个标准,用于处理...

Global site tag (gtag.js) - Google Analytics