2010年12月12日星期日

为什么没有Tp怎么连接SQLite数据库???(转)

摘自:http://www.phpfans.net/ask/MTIzOTk2OA.html

我非常喜欢thinkphp,但是刚开始学习thinkphp,有些地方还不太熟,请高人指点!
最好能给个例子!

谢谢!!
------
昵称: mayi993  时间: 2009-12-17 17:36:00
官方不可能给每个数据库驱动给出代码示例,具体在使用的时候有什么错误提示可以明确提出。
昵称: thinkphp  时间: 2009-12-17 23:31:00
我是用TP连接SQLite数据库,数据库里的内容读出来了,但是在网页的最下面出现一个错误,
Fatal error: Exception thrown without a stack frame in Unknown on line 0
------------
不知道怎么解决???
昵称: mayi993  时间: 2009-12-18 09:17:00
配置
return array(
    'DB_TYPE'=>'sqlite',
        'DB_NAME'=>'Mayi_db/CMS.sdb',
        'DB_PREFIX'=>'CMS_',
        );

读取
$test=M('Admin');
$list1=$test->findAll();
dump($list1);


模型
class AdminModel extends Model{

    function AdminModel() {
    }
}

-------------------------
请高手指点!!!!!
-
昵称: mayi993  时间: 2009-12-18 09:20:00
config.php中sqlite参数如下:
        'DB_TYPE'=>'sqlite',
        'DB_NAME' => 'demo2.sqlite',
        'DB_PREFIX'=>'',
-----------------------
Fatal error: Exception thrown without a stack frame in Unknown  on line 0
上面错误出现,是由于DBsqlite.class.php中的public function close这个函数的原因,sqlite_close()方法没有返回值,所以,无论数据库连接是否关闭,if中的报错都会执行。
将if中sqlit_close()前的叹号去掉就可以了。当然,也可注释掉if中的报错code
昵称: garnono  时间: 2010-11-17 17:04:00
config.php中sqlite参数如下:
        'DB_TYPE'=>'sqlite',
        'DB_NAME' => 'demo2.sqlite',
        'DB_PREFIX'=>'',
-------------------
Fatal error: Exception thrown without a stack frame in Unknown  on line 0
上面错误出现,是由于DBsqlite.class.php中的public function close这个函数的原因,sqlite_close()方法没有返回值,所以,无论数据库连接是否关闭,if中的报错都会执行。
将if中sqlit_close()前的叹号去掉就可以了。当然,也可注释掉if中的报错code
昵称: garnono  时间: 2010-11-17 17:04:00

flex中将图片保存成xml文件存入本地(转)

我们知道Flex对于本地的限制比AIR要大,当我们想保存一个由Flex生成的文件必须借由服务器来完成,现在有一个需求就是,用户想保存Flex生成 的图片在本地,我们要完成这个过程,必须先将Flex生成的图片转换为通用的数据格式,即ByteArray,然后由后台程序帮助写文件,形式上类似先上 传,再下载,只不过中间不用保存实际的物理文件。
源码的编辑:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  3. <mx:Script>
  4. <![CDATA[
  5. import mx.graphics.codec.JPEGEncoder;
  6. import mx.graphics.ImageSnapshot;
  7. private function saveAs(){
  8. var en:JPEGEncoder = new JPEGEncoder(100); //压缩图片,100是指质量
  9. var ba:ByteArray=en.encode(ImageSnapshot.captureBitmapData(img));//将控件转为BitmapData后再转为ByteArray
  10. var request:URLRequest = new URLRequest("/TestForLCDS/servlet/UploadServlet");
  11. request.method="POST";
  12. request.data=ba;
  13. request.contentType = "application/octet-stream"; //这个很重要,设置成流数据
  14. navigateToURL(request,"_blank"); //因为要浏览器触发下载事件,所以就不用异步方式打开连接了
  15. }
  16. ]]>
  17. </mx:Script>
  18. <mx:Button x="228" y="10" label="另存为本地图片" click="saveAs()"/>
  19. <mx:Image id="img" x="10" y="10" source="img.jpg" width="200" height="200" scaleContent="false"/>
  20. </mx:Application>

后台java
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)
  2. throws ServletException, IOException {

  3. response.setContentType("application/x-download"); //内容是下载
  4. response.setHeader("Content-Disposition","attachment;filename=" + "test.jpg");//文件名,可以进一步处理
  5. //读数据
  6. BufferedInputStream inputStream = new BufferedInputStream(request.getInputStream());
  7. OutputStream outputStream = response.getOutputStream();
  8. byte [] bytes = new byte[1024];
  9. int v;
  10. //写数据
  11. while((v=inputStream.read(bytes))>0){
  12. outputStream.write(bytes,0,v);
  13. }
  14. outputStream.flush();
  15. outputStream.close();
  16. inputStream.close();
  17. }

  18. }
摘自:http://www.eb163.com/club/forum.php?mod=viewthread&tid=4165&page=1

php读取二进制文件流生成图片(转)

Php代码
  1. $imgString为二进制文件流  
  2.   
  3.   
  4.     $file_dir="test.jpg";  
  5.     if($fp = fopen($file_dir,'w')){  
  6.       if(fwrite($fp,$img)){  
  7.              fclose($fp);      
  8.           }  
  9.     } 
摘自:http://lhx1026.javaeye.com/blog/503262

flex图片剪切示例--预览、保存到本地、保存到服务器(附源码)(转)

图片剪切功能:

效果图:






flex代码:

 

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()" xmlns:local="astion.*">
 
<mx:Script>
  
<![CDATA[
   import mx.controls.Image;
   import mx.graphics.ImageSnapshot;
   import flash.net.FileReference;
   import mx.graphics.codec.JPEGEncoder;
   import mx.managers.PopUpManager;
   import mx.containers.TitleWindow;
   import mx.controls.Alert;
   import mx.events.CloseEvent;
   import mx.core.IFlexDisplayObject;
   import mx.utils.*;
   import mx.core.Application;
   import astion.Dot;
   import astion.ScaleBox;
   
   public static const LINE_WIDTH:Number = 1;//缩放边框宽度
   private var file:FileReference;
   public var IMAGE_URL:String="http://localhost:8080/cutPicuter/aa/aa.jpg";
   private var loader:Loader;
   private var bmp:Bitmap;
            private var stream:URLStream;
            public var realPath:String="D:\myWorkSpace\cutPicuter\WebRoot\aa\aa.jpg";
   
   //初始化数据
   private function init():void{
    this.loader = new Loader();
                this.stream = new URLStream();
                this.loader.contentLoaderInfo.addEventListener(Event.COMPLETE,this.onComplete);
                this.loader.load(new URLRequest(encodeURI(this.IMAGE_URL)));//解决中文乱码
                this.stream.load(new URLRequest(encodeURI(this.IMAGE_URL)));
                this.stream.addEventListener(Event.COMPLETE,this.onLoaded);
   }
   private function onLoaded(e:Event):void
            {                                
                var bytearray:ByteArray = new ByteArray();    
                this.stream.readBytes(bytearray);
                
                if(this.stream.connected)
                    this.stream.close();
                    
                this.loader.loadBytes(bytearray);
            }
            private function onComplete(e:Event):void
            {
                try
                {
                    this.bmp = this.loader.content as Bitmap;
                    var showImage:Image= new Image();
                    showImage.source=this.loader.content;
                    canvas.addChild(showImage);
                    canvas.setChildIndex(box,1);
                    canvas.setChildIndex(showImage,0);
                }
                catch(e:Error)
                {
                    
                }
            }
   
   //截图,显示缩放选择框
   private function doCapture():void{
    box.x = 100;
    box.y = 100;
    box.visible = true;
   }
   
   //获取缩放选择框内的图像
   private function getImg():BitmapData{
    //截取整个区域
    box.scaleEnable = false;
    var bmp:BitmapData = ImageSnapshot.captureBitmapData(canvas);
    box.scaleEnable = true;
    
    //矩形为要截取区域                
                var re:Rectangle = new Rectangle(box.x+LINE_WIDTH,box.y+LINE_WIDTH,box.boxWidth-LINE_WIDTH,box.boxHeight-LINE_WIDTH); 
                var bytearray:ByteArray = new ByteArray();   
                //截取出所选区域的像素集合                        
                bytearray = bmp.getPixels(re); 
                
                
                var imgBD:BitmapData = new BitmapData(box.boxWidth-LINE_WIDTH,box.boxHeight-LINE_WIDTH);       
                //当前的bytearray.position为最大长度,要设为从0开始读取       
                bytearray.position=0;            
                var fillre:Rectangle = new Rectangle(0,0,box.boxWidth-LINE_WIDTH,box.boxHeight-LINE_WIDTH);
                //将截取出的像素集合存在新的bitmapdata里,大小和截取区域一样
                imgBD.setPixels(fillre,bytearray);
                
                return imgBD;
   }
   
   //预览图片
   private function doScan():void{
    var t:TitleWindow = new TitleWindow();
    t.showCloseButton=true;
    t.addEventListener(CloseEvent.CLOSE,closeWindow);
    t.width = box.boxWidth+t.getStyle("borderThickness");
    t.height =box.boxHeight+t.getStyle("borderThickness")+t.getStyle("headerHeight");
    var img:Image = new Image();
    img.width = box.boxWidth;
    img.height = box.boxHeight; 
    img.source = new Bitmap(getImg());
    t.addChild(img);
    PopUpManager.addPopUp(t,this,true);
    PopUpManager.centerPopUp(t);
   }
   
   private function closeWindow(e:CloseEvent):void{            
                var t:TitleWindow = e.currentTarget as TitleWindow;                    
                PopUpManager.removePopUp(t);                
            }
            
            //保存图片到本地
   private function downloadPicture():void{
    file=new FileReference();
    file.addEventListener(Event.COMPLETE,downloadComplete);
    file.save(new JPEGEncoder(80).encode(getImg()),"default.jpg");
   }
   
   private function downloadComplete(event:Event):void{
    Alert.show("成功保存图片到本地!","提示");
   }
   
   //保存图片到服务器即覆盖原来的图片
   private function save():void{
    Alert.show("是否保存剪切图片?","提示",3, this, function(event:CloseEvent):void {
          if (event.detail==Alert.YES){
           var request:URLRequest = new URLRequest("http://localhost:8080/cutPicuter/servlet/FileManagerSaveFileServlet?realPath="+encodeURIComponent(StringUtil.trim(realPath)));
     request.method=URLRequestMethod.POST;
     request.contentType = "application/octet-stream";
     request.data = new JPEGEncoder(80).encode(getImg());
     var loader:URLLoader = new URLLoader();
     loader.load(request);
     loader.addEventListener(Event.COMPLETE,saveResult);

          }});
   }
   
   private function saveResult(event:Event):void{
    Application.application.reLoadFolderFiles(realPath.substr(0,realPath.lastIndexOf("\\")));
    Alert.show("保存剪切图片成功","提示");
   }
  
]]>
 
</mx:Script>
 
<mx:HBox x="0" y="0">
        
<mx:LinkButton label="剪裁" click="doCapture();" icon="@Embed('assets/cut.png')"/>
        
<mx:LinkButton label="预览" click="doScan();" icon="@Embed('assets/ok.png')"/>
        
<mx:VRule height="22"/>
        
<mx:LinkButton label="保存"  click="save()"  icon="@Embed('assets/save.png')"/>
        
<mx:LinkButton label="另存为" click="downloadPicture();" icon="@Embed('assets/saveAs.png')"/>
    
</mx:HBox>
 
<mx:Canvas id="canvas" y="23" x="1">
 
<local:ScaleBox id="box" visible="false" y="0" x="0" width="100" height="100"/>
 
</mx:Canvas>
</mx:Application>



java代码:

 

package com;


import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

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

/**
 * Servlet implementation class FileManagerSaveFileServlet
 
*/
public class FileManagerSaveFileServlet extends HttpServlet {
 
 
private int len=0;//处理流
 private int mm=0;//重命名
 private String fileName="";//文件原名
 private String extName="";//文件扩展名
 private String tempFileName="";//文件名加扩展名
 
 
public void doGet(HttpServletRequest request, HttpServletResponse response)    
 
throws ServletException, IOException {    
 processRequest(request, response);    
 }    
   
 
public void doPost(HttpServletRequest request, HttpServletResponse response)    
  
throws ServletException, IOException {    
 processRequest(request, response);    
 }    
 
 
public void processRequest(HttpServletRequest request, HttpServletResponse response)

    
throws ServletException, IOException {
  request.setCharacterEncoding(
"utf-8");
  String realPath
=request.getParameter("realPath");
  
//System.out.println("FMSFS-->realPath:"+realPath);
  response.setContentType("application/octet-stream");
  InputStream is 
= request.getInputStream();
  
try {
  
int size = 0;
  
byte[] tmp = new byte[100000];
  
  tempFileName
=realPath.substring(realPath.lastIndexOf("\\")+1);//切割获得文件名加扩展名
  fileName=tempFileName.substring(0,tempFileName.lastIndexOf("."));//切割获得文件名
  
//确保获得真实的文件名如:1(1)可以获得真实为1,
  if(fileName.indexOf("(")!=-1){
   fileName
=fileName.substring(0,fileName.indexOf("("));
  }
  
  extName
=tempFileName.substring(tempFileName.lastIndexOf("."));//切割获得扩展名
  
  
//调用递归方法
  fileName+=reNameFile(realPath.substring(0,realPath.lastIndexOf("\\")+1),fileName,extName);
  
// 创建一个文件夹用来保存发过来的图片;
  File f = new File(realPath.substring(0,realPath.lastIndexOf("\\")+1)+fileName+extName);
  DataOutputStream dos 
= new DataOutputStream(new FileOutputStream(f));
  
while ((len = is.read(tmp)) != -1) {
  dos.write(tmp, 
0, len);
  size 
+= len;
  }
  dos.flush();
  dos.close();
  } 
catch (IOException e) {
  e.printStackTrace();
  }
 }
 
 
//递归来重命名文件名
 String str="";
 
public String reNameFile(String realPath,String filename,String extName){
  File file 
=new File(realPath+"\\"+filename+extName);
  str
="";
        
if(file.exists()){
         mm
++;
         str
="_"+mm;
         reNameFile(realPath,fileName
+str,extName);
        }
else{
         
if(mm!=0){
      str
="_"+mm;
         }
        }
  
return str;
 }
}

 


 

源码: flex图片剪切示例


原创人员:Denny

摘自:http://www.blogjava.net/obpm/archive/2010/09/01/330501.html

PHP对象编程实现3D饼图-PHP教程,PHP应用(转)

<?php

//公用函数

//把角度转换为弧度
function deg2arc($degrees) {
return($degrees * (pi()/180.0));
}

//rgb
function getrgb($color){
$r=($color>>16) & 0xff;
$g=($color>>8) & 0xff;
$b=($color) & 0xff;
return (array($r,$g,$b));
}

// 取得在椭圆心为(0,0)的椭圆上 x,y点的值
function pie_point($deg,$va,$vb){
$x= cos(deg2arc($deg)) * $va;
$y= sin(deg2arc($deg)) * $vb;
return (array($x, $y));
}


//3d饼图类

class pie3d{

var $a; //椭圆长半轴
var $b; //椭圆短半轴
var $dataarray; //每个扇形的数据
var $colorarray; //每个扇形的颜色 需求按照十六进制书写但前面不加0x
//为边缘及阴影为黑色

function pie3d($pa=100,$pb=60,$sdata="100,200,300,400,500", $scolor="ee00ff,dd0000,cccccc,ccff00,00ccff")
{
$this->a=$pa;
$this->b=$pb;
$this->dataarray=split(",",$sdata);
$this->colorarray=split(",",$scolor);
}

function seta($v){
$this->a=$v;
}

function geta(){
return $this->a;
}

function setb($v){
$this->b=$v;
}

function getb(){
return $this->b;
}

function setdataarray($v){
$this->dataarray=split(",",$v);
}

function getdataarray($v){
return $this->dataarray;
}

function setcolorarray($v){
$this->colorarray=split(",",$v);
}

function getcolorarray(){
return $this->colorarray;
}


function drawpie(){
$image=imagecreate($this->a*2+40,$this->b*2+40);
$piecenterx=$this->a+10;
$piecentery=$this->b+10;
$doublea=$this->a*2;
$doubleb=$this->b*2;
list($r,$g,$b)=getrgb(0);
$colorborder=imagecolorallocate($image,$r,$g,$b);
$datanumber=count($this->dataarray);

//$datatotal
for($i=0;$i<$datanumber;$i++) $datatotal+=$this->dataarray[$i]; //算出数据和

//填充背境
imagefill($image, 0, 0, imagecolorallocate($image, 0xff, 0xff, 0xff));

/*
** 画每一个扇形
*/
$degrees = 0;
for($i = 0; $i < $datanumber; $i++){
$startdegrees = round($degrees);
$degrees += (($this->dataarray[$i]/$datatotal)*360);
$enddegrees = round($degrees);
$percent = number_format($this->dataarray[$i]/$datatotal*100, 1);
list($r,$g,$b)=getrgb(hexdec($this->colorarray[$i]));
$currentcolor=imagecolorallocate($image,$r,$g,$b);
if ($r>60 and $r<256) $r=$r-60;
if ($g>60 and $g<256) $g=$g-60;
if ($b>60 and $b<256) $b=$b-60;
$currentdarkcolor=imagecolorallocate($image,$r,$g,$b);
//画扇形弧
imagearc($image,$piecenterx,$piecentery,$doublea,$doubleb,$startdegrees,$enddegrees,$currentcolor);
//画直线
list($arcx, $arcy) = pie_point($startdegrees , $this->a , $this->b);
imageline($image,$piecenterx,$piecentery,floor($piecenterx + $arcx),floor($piecentery + $arcy),$currentcolor);
//画直线
list($arcx, $arcy) = pie_point($enddegrees,$this->a , $this->b);
imageline($image,$piecenterx,$piecentery,ceil($piecenterx + $arcx),ceil($piecentery + $arcy),$currentcolor);
//填充扇形
$midpoint = round((($enddegrees - $startdegrees)/2) + $startdegrees);
list($arcx, $arcy) = pie_point($midpoint, $this->a*3/4 , $this->b*3/4);

imagefilltoborder($image,floor($piecenterx + $arcx),floor($piecentery + $arcy), $currentcolor,$currentcolor);
imagestring($image,2,floor($piecenterx + $arcx-5),floor($piecentery + $arcy-5),$percent."%",$colorborder);

//画阴影
if ($startdegrees>=0 and $startdegrees<=180){
if($enddegrees<=180){
for($k = 1; $k < 15; $k++)
imagearc($image,$piecenterx, $piecentery+$k,$doublea, $doubleb, $startdegrees, $enddegrees, $currentdarkcolor);
}else{
for($k = 1; $k < 15; $k++)
imagearc($image,$piecenterx, $piecentery+$k,$doublea, $doubleb, $startdegrees, 180, $currentdarkcolor);
}

}
}

/*到此脚本已生了一幅图像了
**目前需要的是把他发到浏览器上,重要的一点是要将标头发给浏览器,让他知道是个gif文件。不然的话你只能看到一堆奇怪的乱码
*/
//输出生成的图片
header("content-type: image/gif");
imagegif($image);
imagedestroy($image);
}//end drawpie()
}//end class


//实现

$objp = new pie3d();
$objp->drawpie();
?>

摘自:http://www.sudu.cn/info/html/edu/20071226/34973.html

flex post数据到动态页面(转)

public function submit():void{
   
    //要请求的URL
    var request:URLRequest = new URLRequest("
http://localhost:8086/test.do") ;
    var load:URLLoader = new URLLoader() ;
   //URL参数
    var variables:URLVariables = new URLVariables();
   
    //variables.+后面的参数 表示要提交的参数。
    variables.content = content.text;
   
    variables.no = 1001 ;
   //提交的方式
    request.method=URLRequestMethod.POST;
   
    //提交的数据
    request.data=variables ;
   
    load.dataFormat = URLLoaderDataFormat.TEXT ;
    load.load(request) ;
   
   }

后台通过:

String content = request.getParameter("content") 获取;

String no = request.getParameter("no ") 获取;


摘自:http://hi.baidu.com/minux2007/blog/item/e858905011e1ac040df3e3e4.html

Flex + PHP 实现上传文件(包括进度条功能)(转)

摘自:http://hi.baidu.com/jianzl/blog/item/3b7e22611e0df06c0c33fad4.html

参考网上代码实现的FLEX+PHP上传文件功能

upload.mxml内容:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" borderColor="#FFFFFF"
backgroundGradientAlphas="[1.0, 1.0]"
backgroundGradientColors="[#FFFFFF, #FFFFFF]"
height="30" width="420"
initialize="init('')">
<mx:Script>
    <![CDATA[
    public var file_fr:FileReference = new FileReference();
    public var LI:LoaderInfo;
   
    var list_obj:Object = new Object();
   
    var max_size = 0;
   
    //保存文件地址
    var up_url = "save.php";
   
    //进度条颜色
    var bg_color = "";
   
    //上传文件类型
    var limit_type="";
   
    //保存文件的主目录
    var savemainpath="";

    //当点击浏览按钮时
private function brownsfile():void{
   if (limit_type != "")
   {
    var s:String = "";
    var arr:Array = limit_type.split("|");
    var fst:Number = 1;
    for(var i=0;i<arr.length;i++)
    {
     if (arr[i] == "") continue;
     if (!fst) s+= ';';
     s += "*."+arr[i];
     fst = 0;
    }
    var browseFilter:FileFilter = new FileFilter("受限文件("+s+")", s);

    file_fr.browse([browseFilter]);//.browse([{description: "受限文件("+s+")", extension: s}]);
   }
   else
      file_fr.browse();
   configureListeners(file_fr);
}

//绑定监听
private function configureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.CANCEL, cancelHandler);
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            //dispatcher.addEventListener(Event.OPEN, openHandler);
            dispatcher.addEventListener(ProgressEvent.PROGRESS, onProgress);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.addEventListener(Event.SELECT, fileSelected);
            dispatcher.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler);
     }


//当选中文件时
     public function fileSelected(event:Event):void{
     file_fr = FileReference(event.target);

   upload_butn.enabled = true;
   name_txt.text = file_fr.name + " ("+deal_size(file_fr.size)+")";
   if (file_fr.size > max_size && max_size != 0)
   {
    init("单个上传文件不能大于 "+deal_size(max_size));
   }
}

//当点击上传或取消按钮时
private function uploadfile() {
   if (upload_butn.label == "上传")
   {
    var variables:URLVariables = new URLVariables();
    variables.savepath = savemainpath;   
   
    var uploadURL = new URLRequest();
            uploadURL.url = up_url;
            uploadURL.data = variables;
            uploadURL.method=URLRequestMethod.POST;
           
    file_fr.upload(uploadURL);
    upload_butn.label = "取消";
    browse_butn.enabled = false;
   }else
   {
    file_fr.cancel();
    init("");
   }
}
//正在上传中时
private function onProgress(event:ProgressEvent)
{
   var tmploaded:Number = event.bytesLoaded;
   //var tmptotal:Number = event.bytesTotal;
   name_txt.text = "正在上传"+file_fr.name+"("+deal_size(file_fr.size)+"): "+Math.floor(tmploaded*100/file_fr.size)+"%";
   drawRec(tmploaded,file_fr.size);
}

    //上传完成并返回数据时
    private function uploadCompleteDataHandler(event:DataEvent):void{
     var result:XML = new XML(event.data);
     var tmpStr = result.toString();
     tmpStr = tmpStr.substring(0,6);
     if(tmpStr=="Error:")
         init("文件上传失败:Error=[403 or 404]");
        else
           ExternalInterface.call("uploadJSAction", result.toString(),savemainpath);
}

//上传完成时
    private function completeHandler(event:Event){
     init("文件上传完毕!");
}

//文件读写失败时
public function ioErrorHandler(event:IOErrorEvent)
{
   init("文件上传失败: " + file_fr.name+";Error:文件 I/O 错误。");
}

//安全错误
public function securityErrorHandler(fileRef:FileReference,error)
{
   init( "安全设置错误 " + file_fr.name + ":" + error);
}

//HTTP错误,当出现其他错误时,save.php也会发出404错误
public function httpStatusHandler(event:HTTPStatusEvent)
{
   init("文件上传失败!"+event.status);
}


    //取消上传时
    public function cancelHandler(){
        init("");
    }

    //初始化
public function init(s:String):void{
   //获得参数对象               
        var param:Object = Application.application.parameters;
        //上传最大文件
        max_size = param["maxsize"];
        max_size = (!max_size)?20*1024:max_size*1024;
       
        //保存文件地址
        up_url = param["savefile"];
        up_url = (up_url=="")?"save.php":up_url;

        //进度条颜色
        bg_color = param["bgcolor"];
        bg_color = (bg_color == "")?Math.random()*0xff5079:"0x"+bg_color;
   
        //上传文件类型
        limit_type = param["limit"];
        limit_type = (limit_type=="")?"":limit_type;
       
        //上传文件类型
        savemainpath = param["imgpath"];
        savemainpath = (savemainpath=="")?"":savemainpath;
       
       
   progress_cav.setStyle("backgroundColor",bg_color);
   if (!s) name_txt.text = "选择一个文件";//+strTemp;
   else name_txt.text = s;
   browse_butn.enabled = true;
   upload_butn.enabled = false;
   upload_butn.label = "上传";
   progress_cav.width=0;
}
   
    //得到URL传递的参数值
private function get_val(s,val)
{
   var arr = s.split("?");
   if (!arr[1]) return "";
   s = arr[1];
   arr = s.split(val+"=");
   if (!arr[1]) return "";
   s = arr[1];
   arr = s.split("&");
   return arr[0];
}
   
    /*处理文件大小表示方法*/
private function deal_size(s:Number):String {
   var danwei:Array = ["Byte","KB","MB","GB" ];
   var d:Number = 0;
   while ( s >= 900 )
   {
    s = Math.round(s*100/1024)/100;
    d++;
   }
   return s+" "+danwei[d];
}

//画进度背景条
private function drawRec (i:Number,t:Number):void {
   var per:Number = Math.floor(i*100/t)/100;
   var tmpWidth:Number = this.width * per;
   progress_cav.width=tmpWidth;
}

    ]]>
</mx:Script>
<mx:Canvas x="0" y="0" width="10" height="30" backgroundColor="#5075FF" borderColor="#FFFFFF" color="#FFFFFF" borderStyle="none" id="progress_cav">
</mx:Canvas>
<mx:TextInput x="307" y="4" height="22" width="51" borderStyle="none" cornerRadius="4"/>
<mx:TextInput x="363" y="4" height="22" width="51" borderStyle="none" cornerRadius="4"/>
<mx:Button x="363" y="4" label="上传" fontSize="12" id="upload_butn" enabled="false" click="uploadfile();" height="22" cornerRadius="0"/>
<mx:Button x="307" y="4" label="浏览" fontSize="12" id="browse_butn" click="brownsfile();" height="22" cornerRadius="0"/>
<mx:TextInput x="4" y="4" width="300" themeColor="#B5B5B5" enabled="true" editable="false" borderStyle="solid" id="name_txt" text="选择一个文件" fontSize="12" color="#000000" height="22"/>
</mx:Application>

saveimg.php内容如下:

<?php

//取得保存文件的主目录
$savepath = $_POST["savepath"];

foreach($_FILES as $f)
{
session_start();
//取得服务器当前时间:HHMISSMMM
$saveFileName = date("dHis");
$saveFileName = substr(session_id(),0,8)."_".$saveFileName.substr(microtime(),2,4);

//取得上传的文件类型
$uploadFileType = strtolower($f['name']);
//echo $uploadFileType;
//exit;
$uploadFileType = strrchr($uploadFileType,".");

//设定保存的文件名
$saveFileName = $saveFileName.$uploadFileType;

//上传文件保存目录
$UploadPath = "../../upload/".$savepath."/";


//根据月份创建子目录
$nowMonth = date("Ym");
mkdir($UploadPath.$nowMonth, 0700);
$UploadPath = $UploadPath.$nowMonth."/";
//处理中文名
if (function_exists("iconv")) $f[name] = iconv("UTF-8","GB2312",$f[name]);
//检查是否已经存在同名文件
if (file_exists($f[name])) echo "Error:403 Found Same Filename";
//保存文件
if (!@move_uploaded_file($f["tmp_name"],$UploadPath.$saveFileName))
    echo "Error:404 Not Found";
else
    echo $nowMonth."/".$saveFileName;
}
?>

测试页面内容:test.html内容:

<label>上传图片:</label>
       <input type="hidden" name="uploadfile" id="uploadfile" value="">
       <span id="uploadSpanDiv"></span>
            <span id="uploadSwfSpanDiv" style="display:">
        <embed
               src="./swf/upload.swf?savefile=./save/savedpjcimg.php&limit=jpeg|gif|jpg&maxsize=204800&bgcolor=ff5079&imgpath=dpjcimages"
               width="420"
               height="30"
               align="middle"
               play="true"
               loop="false"
               quality="high"
               type="application/x-shockwave-flash">
              </embed>
            </span>


相关JS内容:

function uploadJSAction(fileName,imgpath){
    $("#uploadSpanDiv").html("<a href='javascript:showimg(\""+fileName+"\",\""+imgpath+"\")'>"+fileName+"</a> <a href='javascript:showSwf();'>删除文件</a>");
    $("#uploadSpanDiv").css("display","");
    $("#uploadSwfSpanDiv").css("display","none");
    $("#uploadfile").val(fileName);
}
function showSwf(){
    $("#uploadSwfSpanDiv").css("display","");
    $("#uploadSpanDiv").css("display","none");
    $("#uploadfile").val("");
}

function showimg(fileName,imgpath){
   $(document).jdialog({title:"预览上传的图片",content : "url:get?show_upload_image.php?img="+fileName+"&path="+imgpath});
}