Flex 基于Http方式上传图片(转)

首先下载 commons-fileupload-1.2.1.jar和commons-io-1.1.jar 
flex端代码: 


<?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.events.*;

            
import mx.controls.Alert;
            
import mx.events.CloseEvent;
            
import mx.managers.CursorManager;

            
private var file:FileReference;
            
private var byteArray:ByteArray;
            
private var bitmapData:BitmapData;
            
private var loader:Loader=new Loader();

            
private function init():void
            
{
                Security.allowDomain(
"*");
                file
=new FileReference();
                file.addEventListener(Event.COMPLETE, fileReferenceCompleteHandler);
                file.addEventListener(Event.SELECT, fileReferenceSelectHandler);
            }


            
//选择上传的图片
            private function choose():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 toUpload():void
            
{
                
if (bitmapData == null)
                
{
                    Alert.show(
"请您先选择要上传的图片");
                }

                
else
                
{
                    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 + "%";
                
if (e.bytesLoaded == e.bytesTotal)
                
{
                    CursorManager.removeBusyCursor();
                }

            }


            
//上传图片到服务器
            private function proceedWithUpload(e:CloseEvent):void
            
{
                
if (e.detail == Alert.YES)
                
{
                    
//进度监听
                    file.addEventListener(ProgressEvent.PROGRESS, onProgress);
                    var request:URLRequest
=new URLRequest("http://localhost:8080/FileUploaded");
                    
//设置鼠标忙状态
                    CursorManager.setBusyCursor();
                    
try
                    
{
                        file.upload(request);
                        Alert.show(
"恭喜你,上传成功");
                    }

                    
catch (error:Error)
                    
{
                        Alert.show(
"上传失败");
                        trace(
"上传失败");
                    }


                }

            }


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


            
//载入本地图片
            private function fileReferenceCompleteHandler(e:Event):void
            
{
                byteArray
=file.data;
                loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
                loader.loadBytes(byteArray);
            }


            
//图片载入完成显示在预览框中
            private function loaderCompleteHandler(e:Event):void
            
{
                var bitmap:Bitmap
=Bitmap(loader.content);
                bitmapData
=bitmap.bitmapData;
                img.source
=bitmap;
            }


            
//选择文件动作监听
            private function fileReferenceSelectHandler(e:Event):void
            
{
                file.removeEventListener(ProgressEvent.PROGRESS, onProgress);
                file.load();
            }

        ]]
>
    
</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
="toUpload();"/>
        
</mx:VBox>
        
<mx:Panel width="469"
                  height
="392"
                  verticalGap
="0"
                  horizontalAlign
="center"
                  verticalAlign
="middle"
                  x
="408"
                  y
="129"
                  layout
="absolute">
            
<mx:Button label="选择文件"
                       click
="choose();"
                       x
="178"
                       y
="9"/>
            
<mx:Image id="img"
                      width
="400"
                      height
="300"
                      x
="36"
                      y
="44"/>

        
</mx:Panel>

    
</mx:Canvas>
</mx:Application>

java servlet端代码 

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

public class FileUploaded extends HttpServlet {

    
// 定义文件的上传路径
    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(
"to upload picture !");
        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() 
+ "结束");
        }

    }


    
protected void doGet(HttpServletRequest request,
            HttpServletResponse response) 
throws ServletException, IOException {
        processRequest(request, response);
    }


    
protected void doPost(HttpServletRequest request,
            HttpServletResponse response) 
throws ServletException, IOException {
        processRequest(request, response);
    }


    
public String getServletInfo() {
        
return "Short description";
    }


}


web.xml 文件内容:
<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
    
     
<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>
    
    
<session-config>
        
<session-timeout>35</session-timeout>
    
</session-config>
    
<mime-mapping>
        
<extension>html</extension>
        
<mime-type>text/html</mime-type>
    
</mime-mapping>
    
<mime-mapping>
        
<extension>txt</extension>
        
<mime-type>text/plain</mime-type>
    
</mime-mapping>
    
</web-app>

FLEX端如果出现安全沙箱的问题:是由于在tomcat环境下没有声明应用程序能被外部访问. 

在程序的部署文件夹下添加crossdomain.xml文件.文件内容为: 
<?xml version="1.0"?> 

<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> 

<cross-domain-policy> 

<allow-access-from domain="*" secure="false"/> 
<allow-http-request-headers-from domain="*" headers="*" secure="false"/> 

</cross-domain-policy>
http://blog.163.com/geliang0021@126/blog/static/32322329201111295559423/
http://wenku.baidu.com/view/9b1fceb769dc5022aaea00e9.html

posted on 2012-09-11 22:36 youngturk 阅读(4106) 评论(0)  编辑  收藏 所属分类: Java基础Flex DEVservlet


只有注册用户登录后才能发表评论。


网站导航:
 
<2012年9月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

导航

统计

公告

this year :
1 jQuery
2 freemarker
3 框架结构
4 口语英语

常用链接

留言簿(6)

随笔分类

随笔档案

文章分类

文章档案

相册

EJB学习

Flex学习

learn English

oracle

spring MVC web service

SQL

Struts

生活保健

解析文件

搜索

最新评论

阅读排行榜

评论排行榜