`
stuhack0303
  • 浏览: 14659 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Flex+Java Servlet文件上传实例

阅读更多
资源都是来自网上。本实例将展示使用Flex和java servlet上传文件。
事前准备就是到http://commons.apache.org下载common-fileupload-1.1.1.jar以及common-io-1.2.jar两个包。
前台Flex代码:

Java代码
1.<?xml version="1.0" encoding="utf-8"?>  
2.<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*" creationComplete="init();">  
3.<mx:Script>  
4.<![CDATA[  
5.import flash.net.FileReference;  
6.import mx.controls.Alert;  
7.import mx.events.CloseEvent;  
8.import flash.events.*;  
9. 
10.private var file: FileReference;  
11. 
12.private function init(): void{  
13.Security.allowDomain("*");  
14.file = new FileReference();  
15.file.addEventListener(ProgressEvent.PROGRESS, onProgress);  
16.file.addEventListener(Event.SELECT, onSelect);  
17.file.addEventListener(Event.COMPLETE, completeHandle);  
18.}  
19. 
20.private function completeHandle(event:Event):void{  
21.    Alert.show("恭喜你,上传成功");  
22.}  
23. 
24.private function upload(): void{  
25.var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");  
26.var allTypes:Array = new Array(imageTypes);  
27.file.browse(allTypes);  
28.file.browse();  
29.}  
30.private function onSelect(e: Event): void{  
31.Alert.show("上传 " + file.name + " (共 "+Math.round(file.size)+" 字节)?",  
32."确认上传",  
33.Alert.YES|Alert.NO,  
34.null,  
35.proceedWithUpload);  
36.}  
37. 
38.private function onProgress(e: ProgressEvent): void{  
39.lbProgress.text = " 已上传 " + e.bytesLoaded  
40.+ " 字节,共 " + e.bytesTotal + " 字节";  
41.var proc: uint = e.bytesLoaded / e.bytesTotal * 100;  
42.bar.setProgress(proc, 100);  
43.bar.label= "当前进度: " + " " + proc + "%";  
44.}  
45. 
46.private function proceedWithUpload(e: CloseEvent): void{  
47.if (e.detail == Alert.YES){  
48.var request: URLRequest = new URLRequest("http://localhost:8080/FileUploaded/FileUploaded");  
49.try {  
50.file.upload(request);  
51.} catch (error:Error) {  
52.trace("上传失败");  
53.}  
54. 
55.}  
56.}  
57.]]>  
58.</mx:Script>  
59. 
60.<mx:Canvas width="100%" height="100%" x="10" y="170" fontSize="15">  
61.<mx:VBox width="100%" horizontalAlign="center">  
62.<mx:Label id="lbProgress" text="上传"/>  
63.<mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A" 
64.minimum="0" visible="true" maximum="100" label="当前进度: 0%" 
65.direction="right" mode="manual" width="200"/>  
66. 
67.<mx:Button label="上传文件" click="upload();"/>  
68.</mx:VBox>  
69.</mx:Canvas>  
70.</mx:Application> 
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*" creationComplete="init();">
<mx:Script>
<![CDATA[
import flash.net.FileReference;
import mx.controls.Alert;
import mx.events.CloseEvent;
import flash.events.*;

private var file: FileReference;

private function init(): void{
Security.allowDomain("*");
file = new FileReference();
file.addEventListener(ProgressEvent.PROGRESS, onProgress);
file.addEventListener(Event.SELECT, onSelect);
file.addEventListener(Event.COMPLETE, completeHandle);
}

private function completeHandle(event:Event):void{
    Alert.show("恭喜你,上传成功");
}

private function upload(): void{
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");
var allTypes:Array = new Array(imageTypes);
file.browse(allTypes);
file.browse();
}
private function onSelect(e: Event): void{
Alert.show("上传 " + file.name + " (共 "+Math.round(file.size)+" 字节)?",
"确认上传",
Alert.YES|Alert.NO,
null,
proceedWithUpload);
}

private function onProgress(e: ProgressEvent): void{
lbProgress.text = " 已上传 " + e.bytesLoaded
+ " 字节,共 " + e.bytesTotal + " 字节";
var proc: uint = e.bytesLoaded / e.bytesTotal * 100;
bar.setProgress(proc, 100);
bar.label= "当前进度: " + " " + proc + "%";
}

private function proceedWithUpload(e: CloseEvent): void{
if (e.detail == Alert.YES){
var request: URLRequest = new URLRequest("http://localhost:8080/FileUploaded/FileUploaded");
try {
file.upload(request);
} catch (error:Error) {
trace("上传失败");
}

}
}
]]>
</mx:Script>

<mx:Canvas width="100%" height="100%" x="10" y="170" fontSize="15">
<mx:VBox width="100%" horizontalAlign="center">
<mx:Label id="lbProgress" text="上传"/>
<mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A"
minimum="0" visible="true" maximum="100" label="当前进度: 0%"
direction="right" mode="manual" width="200"/>

<mx:Button label="上传文件" click="upload();"/>
</mx:VBox>
</mx:Canvas>
</mx:Application>

http://localhost:8080/FileUploaded/FileUploaded就是你自己写的servlet的路径了。

接下来写的是Java Servlet:

Java代码
1.package upload;  
2.import java.io.File;  
3.import java.io.IOException;  
4.import java.io.PrintWriter;  
5.import java.util.Iterator;  
6.import java.util.List;  
7. 
8.import javax.servlet.ServletException;  
9.import javax.servlet.http.HttpServlet;  
10.import javax.servlet.http.HttpServletRequest;  
11.import javax.servlet.http.HttpServletResponse;  
12. 
13.import org.apache.commons.fileupload.FileItem;  
14.import org.apache.commons.fileupload.FileUploadException;  
15.import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
16.import org.apache.commons.fileupload.servlet.ServletFileUpload;  
17. 
18./** 
19. * 
20. * @author crystal 
21. */ 
22.public class FileUploaded extends HttpServlet {  
23. 
24.    /** 
25.     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. 
26.     * @param request servlet request 
27.     * @param response servlet response 
28.     */ 
29.    // 定义文件的上传路径  
30. 
31.    private String uploadPath = "d:\\a\\";  
32. 
33.// 限制文件的上传大小  
34. 
35.    private int maxPostSize = 100 * 1024 * 1024;  
36. 
37.    public FileUploaded() {  
38.        super();  
39.    }  
40. 
41.    public void destroy() {  
42.        super.destroy();  
43.    }  
44. 
45.    protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
46.            throws ServletException, IOException {  
47.        System.out.println("Access !");  
48.        response.setContentType("text/html;charset=UTF-8");  
49.        PrintWriter out = response.getWriter();  
50. 
51.//保存文件到服务器中  
52. 
53.        DiskFileItemFactory factory = new DiskFileItemFactory();  
54.        factory.setSizeThreshold(4096);  
55.        ServletFileUpload upload = new ServletFileUpload(factory);  
56.        upload.setSizeMax(maxPostSize);  
57.        try {  
58.            List fileItems = upload.parseRequest(request);  
59.            Iterator iter = fileItems.iterator();  
60.            while (iter.hasNext()) {  
61.                FileItem item = (FileItem) iter.next();  
62.                if (!item.isFormField()) {  
63.                    String name = item.getName();  
64.                    System.out.println(name);  
65.                    try {  
66.                        item.write(new File(uploadPath + name));  
67.                       // SaveFile s = new SaveFile();  
68. 
69.                       // s.saveFile(name);  
70. 
71.                    } catch (Exception e) {  
72.                        e.printStackTrace();  
73.                    }  
74.                }  
75.            }  
76.        } catch (FileUploadException e) {  
77.            e.printStackTrace();  
78.            System.out.println(e.getMessage() + "结束");  
79.        }  
80.    }  
81. 
82.    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">  
83. 
84.    /** 
85.     * Handles the HTTP <code>GET</code> method. 
86.     * @param request servlet request 
87.     * @param response servlet response 
88.     */ 
89.    protected void doGet(HttpServletRequest request, HttpServletResponse response)  
90.            throws ServletException, IOException {  
91.        processRequest(request, response);  
92.    }  
93. 
94.    /** 
95.     * Handles the HTTP <code>POST</code> method. 
96.     * @param request servlet request 
97.     * @param response servlet response 
98.     */ 
99.    protected void doPost(HttpServletRequest request, HttpServletResponse response)  
100.            throws ServletException, IOException {  
101.        processRequest(request, response);  
102.    }  
103. 
104.    /** 
105.     * Returns a short description of the servlet. 
106.     */ 
107.    public String getServletInfo() {  
108.        return "Short description";  
109.    }  
110.    // </editor-fold>  
111. 
112.} 
package upload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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 FileUploaded extends HttpServlet {

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

    private String uploadPath = "d:\\a\\";

// 限制文件的上传大小

    private int maxPostSize = 100 * 1024 * 1024;

    public FileUploaded() {
        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");
        PrintWriter out = response.getWriter();

//保存文件到服务器中

        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 {
                        item.write(new File(uploadPath + name));
                       // SaveFile s = new SaveFile();

                       // s.saveFile(name);

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

    // <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>

}
如果使得你的Servlet被访问,你还需要在WEB-INF/web.xml 添加如下的xml语句:[在<web-app>中]
Java代码
1.<!-- For file uploaded -->  
2.   <servlet>  
3.        <servlet-name>FileUploaded</servlet-name>  
4.        <servlet-class>upload.FileUploaded</servlet-class>  
5.    </servlet>  
6. 
7.    <servlet-mapping>  
8.        <servlet-name>FileUploaded</servlet-name>  
9.        <url-pattern>/FileUploaded</url-pattern>  
10.    </servlet-mapping> 
<!-- For file uploaded -->
   <servlet>
        <servlet-name>FileUploaded</servlet-name>
        <servlet-class>upload.FileUploaded</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>FileUploaded</servlet-name>
        <url-pattern>/FileUploaded</url-pattern>
    </servlet-mapping>

效果图:
分享到:
评论

相关推荐

    flex+java文件上传完整实例

    本示例“flex+java文件上传完整实例”提供了一个完善的解决方案,它结合了Adobe Flex前端技术和Java后端技术,实现了用户友好的文件上传功能。Flex是一种开源的RIA(富互联网应用)开发框架,而Java则提供了强大的...

    flex+java+mysql登录

    3. Java后台处理:在Java端,你需要创建一个对应的Servlet或Spring MVC控制器来处理来自Flex的请求。这个控制器会接收到Flex传递过来的登录信息,然后使用JDBC(Java Database Connectivity)API与MySQL数据库进行...

    flex+servlet简单实例

    3. **Servlet配置**:在Servlet端,我们需要配置web.xml文件,声明处理Flex请求的Servlet。例如,可以使用BlazeDS或 GraniteDS这样的服务来提供AMF支持。这些服务允许Servlet容器处理AMF请求,与Flex客户端进行交互...

    flex+java+tomcat集成之后的新建工程

    - **Tomcat 6.x** 是Apache软件基金会的开源Servlet容器,常被用作Java Web应用服务器。 2. **集成环境搭建** - 首先,确保Flash Builder 4.5和MyEclipse 10已经正确安装,并且Tomcat 6.x也已下载并配置好环境...

    Flex + Java 最佳实例(附工程)

    《Flex + Java 最佳实例(附工程)》 在当今的软件开发领域,Flex与Java的结合使用成为了构建富互联网应用程序(RIA)的一种流行选择。Flex作为Adobe开发的开源前端框架,以其强大的图形用户界面(GUI)设计能力,...

    flex+java+mysql

    本项目“flex+java+mysql”是一个用户登录系统,它利用了这些技术的优势,为初学者提供了很好的学习实例。下面将详细阐述这个组合中的各个知识点。 1. Flex:Flex是由Adobe开发的一种开放源代码的开发框架,主要...

    flex+hibernate 实例

    3. **服务创建**:在Flex端,创建一个AMF通道连接到服务器上的服务,这个服务通常是一个Java Servlet,负责处理Flex发来的请求,调用Hibernate方法进行数据操作。 4. **数据访问**:在Flex应用中,使用Service或...

    Flex与Java Servlet交互实例

    本文简单介绍了Flex如何通过servlet连接数据库(Access)。使用的是给后台传递数据的方法。 本文开发使用的软件: Flex3-eclipse plugin Tomcat 6.0 Microsoft access 2003 Eclipse 3.3 各个软件的安装和...

    flex+java+blazeds

    1. **项目结构**:可能有Flex客户端的源代码(.mxml和.as文件)、Java服务器端的类(.java文件)、配置文件(如 BlazeDS 的 services-config.xml 和 flex-servlet.xml)以及可能的数据模型(如JavaBean)。...

    Flex+ActionScript+JAVA等学习教程集合

    Flex是Adobe公司开发的...这个学习教程集合可能包括了各种实例、源码、讲解文档,帮助你深入理解并掌握Flex、ActionScript和Java之间的协同工作。通过学习,你将能够构建出复杂的跨平台RIA,实现前后端数据的无缝交互。

    +Flex+集成到+Java+EE+应用程序的最佳实践(完整源代码)

    由于 BlazeDS 需要将 Java 接口 FlexService 暴露给 Flex 前端,因此,我们在配置文件 remoting-config.xml 中将 FlexService 接口声明为一个服务: 清单 6. 定义 flexService 服务 &lt;destination id="flex...

    链路监控DEMO主要技术FLEX+JAVA

    总的来说,链路监控DEMO是一个结合了FLEX和JAVA技术的实例,为学习者提供了实际操作和理解链路监控系统的机会。通过这个DEMO,开发者不仅可以掌握这两种技术的融合应用,还能了解到监控系统的设计原则和最佳实践,...

    Flex+J2ee实例.

    3. **配置文件**:如flex-servlet.xml(Flex Remoting配置)、web.xml(Java EE的部署描述符)等,这些文件定义了Flex与Java EE之间的通信通道。 4. **数据库脚本**:可能包含SQL文件,用于创建和初始化数据库表...

Global site tag (gtag.js) - Google Analytics