您的位置:首页 > 其它

YUpload补完计划

2014-03-20 19:39 309 查看
http://blog.csdn.net/yukon12345/article/details/6827768

请大家先去看看楼主的文章,然后下载下来就可以用了,但是,还不行,连基本的js交互等都没有做到,于是我修改了一下,下面是修改的核心文件,包括js交互,参数,java的后台交互。

package {
import easis.common.StringUtils;

import fl.controls.RadioButton;
import fl.controls.RadioButtonGroup;
import fl.managers.StyleManager;

import flash.display.GradientType;
import flash.display.Graphics;
import flash.display.Loader;
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.geom.Matrix;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.FileReferenceList;
import flash.net.URLRequest;
import flash.system.Security;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;

/*   presented by yukon12345  (http://hi.baidu.com/yukon_kanzaki/blog/item/b500fd1f77d808f8e1fe0b88.html)
/*
/*   generate from BAIDU
/*   注意:软件遵循MIT使用许可协议(http://zh.wikipedia.org/zh-cn/MIT许可证)
/*   可自由转载,修改和用于商业用途,但使用时必须保留此注释段所有信息 2010-6-14
*/
public class YUploadImg extends Sprite {
private var sizeLimit=2*1024*1024 //2M上传限制(此参数可更改设置)
private var _upURL="http://127.0.0.1/upload/up.php"
//上传地址请设置成你的。如果swf放在和上传处理页面同一网站文件夹,请用相对地址。(此参数可更改设置)
private var _numLimit=20               //最大允许文件数(此参数可更改设置)
private var _descHeight:uint=20;//每一个desc的高度。
private var _noticeCon                 //红色的提醒消息文本容器
private var _statusTex:TextField;     //状态显示文本
private var _urlRequest;
private var _UIWidth=850;             //整个上传工具的宽度高度
private var _UIHeight=390-50;            //ui的高度,这里去掉了几个无用的东西,可以小一点。
private var _headH=50;                //头部。从最顶到灰色标题栏
private var _imgShower;               //装载缩略图组的容器。即灰色线框
private var _imgShowerH=256;          //容器高度
private var _footH=80;                //底部。灰色线框底部下面所有
private var _allowComment:Boolean=false  //允许评论标示
private var _allowReprint:Boolean=false;  //允许转帖标示量
private var _footLine       ;             //底部点状线
private var _sSelectBu     ;             //小选择添加图片按钮
private var _selectBu       ;             //大  选择添加图片按钮
private var _fileQueue=null               //文件引用队列。记录当前在显示容器里的缩略图的文件选择。包括已上传的和格式等错误的
private var _fileRefList    ;             //记录文件浏览框“确定”按下时候返回的文件引用组
private var _foot          ;            //底部容器
private var _uploadBu:UploadBu;                   //上传按钮
private var _uploadingIndex=0     ;      //当前正在上传的索引号
private var _uploadedNum  ;                //已上传了的文件数
private var _uploadingItem ;             //正在上传的缩略图类
private var _isPause    ;                //是否暂停的标量
private var _pauseBu    ;               //暂停按钮
private var _cleanUpBu   ;             //“全部清除”按钮
private var _seletedItemArray=[]   ;    //被选择的缩略图队列
private var _allRightBu     ;            //将选择文件左,右,删除,转按钮
private var _allLeftBu   ;
private var _allDelBu;
private var _tipsIsHide=true   ; //提示条是否显示的标志。
//private var _tipsObj           //提示条对象
//private var r1:RadioButton;
//private var r2:RadioButton;
//private var c1:RadioButton;
//private var c2:RadioButton;
public function YUploadImg(){
if(stage){
init();
}
else{
this.addEventListener(Event.ADDED_TO_STAGE,this.init);
}
//trace("高度:"+this.height+"宽度:"+this.width+"坐标x:"+this.x+"坐标y:"+this.y);
}
public function init(event:Event=null){
this.removeEventListener(Event.ADDED_TO_STAGE,this.init);
Security.allowDomain("*");
if(UploadSettings.allowDesc){
this._imgShowerH+=this._descHeight*2;
}

UploadSettings.uploadUrl =this.loaderInfo.parameters["uploadUrl"] ? (this.loaderInfo.parameters["uploadUrl"]) : ("http://localhost:8080/quickTest/YUploadHandler.jsp");
UploadSettings.max=this.loaderInfo.parameters["max"] &&!isNaN(this.loaderInfo.parameters["max"] )? (parseInt( this.loaderInfo.parameters["max"]) ):8;
UploadSettings.allowDesc=this.obj2Boolean(this.loaderInfo.parameters["allowDesc"],true );
UploadSettings.callBack =this.loaderInfo.parameters["callBack"] ? (this.loaderInfo.parameters["callBack"]) : ("alert");
UploadSettings.perCallBack =this.loaderInfo.parameters["perCallBack"] ? (this.loaderInfo.parameters["perCallBack"]) : ("alert");
UploadSettings.sequenceKey =this.loaderInfo.parameters["sequenceKey"] ? (this.loaderInfo.parameters["sequenceKey"]) : ("sequence");
this._upURL=UploadSettings.uploadUrl;
if(UploadSettings.allowDesc){
this.stage.addEventListener(MouseEvent.CLICK,this.deactiveContr);
}
else{
}
stage.scaleMode=StageScaleMode.NO_SCALE;//不拉伸
_urlRequest=new URLRequest();
_urlRequest.url=_upURL;//文件上传路径
makeHead();
makeBody();
makeFoot();

_fileRefList=new FileReferenceList();
_fileRefList.addEventListener(Event.SELECT,onFRL);
_fileRefList.addEventListener(Event.CANCEL,onFRL);
drawImgShower(0);//绘制显示框
}

private function  makeHead(){//头部分容器
//分界线
var _headLine=new DotLine
_headLine.y=2
addChild(_headLine)
//小"添加图片"按钮
_sSelectBu=new SmallSelectBu();
_sSelectBu.x=2;
_sSelectBu.y=10;
_sSelectBu.addEventListener(MouseEvent.MOUSE_DOWN,onSelectBu);
addChild(_sSelectBu);
//状态输出文本
_statusTex=new TextField();
_statusTex.x=100;
_statusTex.y=10;
_statusTex.height=20;
_statusTex.width=500;
_statusTex.text="最大上传数:"+_numLimit+";图片不超过2M;允许类型:PNG,JPG,GIF,JPEG";
addChild(_statusTex);
//全部清空按钮
_cleanUpBu=new CleanUpBu();
_cleanUpBu.x=30;
_cleanUpBu.y=_headH+5;
_cleanUpBu.addEventListener(MouseEvent.MOUSE_DOWN,function(){
var _tmp_i=_imgShower.numChildren-1;
var _tmp_item;
var _tmp_fr;
var _tmp_j=0;
var _tmp_queuedFR;
var _tmp_hasDeled=false;
while(_tmp_i>=0){//从后向前全部删除
_tmp_item=YItem(_imgShower.getChildAt(_tmp_i));
if(!_tmp_item.uploadOver){
_imgShower.removeChild(_tmp_item);
_fileQueue.splice(_tmp_i,1);
_tmp_hasDeled=true;

}//if有没上传的
_tmp_i--;
}//while1

if(_tmp_hasDeled){
_statusTex.text="已清空未上传的图片";
drawImgShower(_imgShower.numChildren);
}
else{
notice("无可清空图片");
}
if(_fileQueue.length==0){
setEmptyState();
}
})

_allRightBu=new AllRightBu;   //将选择的图片右转
_allRightBu.x=_UIWidth-200;
_allRightBu.y=_headH+5;
_allRightBu.addEventListener(MouseEvent.MOUSE_DOWN,onAllRight);

_allLeftBu=new AllLeftBu;   //将选择的图片左转
_allLeftBu.x=_UIWidth-300;
_allLeftBu.y=_headH+5;
_allLeftBu.addEventListener(MouseEvent.MOUSE_DOWN,onAllLeft);

_allDelBu=new AllDelBu ;  //将选择的图片删除
_allDelBu.x=_UIWidth-100;
_allDelBu.y=_headH+5;
_allDelBu.addEventListener(MouseEvent.MOUSE_DOWN,onAllDel);
}

private function onAllLeft(e:Event){  //当点击右上角标题栏的左转
if(_seletedItemArray.length!=0){

var _tmp_i=0
for each (var _tmp_item in _seletedItemArray){//遍历删除每一个被选择的图片
YItem(_imgShower.getChildAt(_tmp_item.index)).turnLeft();
}
}
else{
notice("无选中图片");
}
}

private function onAllRight(e:Event){
if(_seletedItemArray.length!=0){

var _tmp_i=0
for each (var _tmp_item in _seletedItemArray){//遍历删除每一个被选择的图片
YItem(_imgShower.getChildAt(_tmp_item.index)).turnRight()
}

}
else{
notice("无选中图片");
}

}
private function onAllDel(e:Event){
if(_seletedItemArray.length!=0){

var _tmp_i=0
for each (var _tmp_item in _seletedItemArray){//遍历删除每一个被选择的图片
delImg(_tmp_item.index)
}
_seletedItemArray.length=0
}
else{
notice("无选中图片");
}
}

private function delImg(_tmp_index){//按索引删除图片
_imgShower.removeChildAt(_tmp_index)//删除此图片
_fileQueue.splice(_tmp_index,1)  //待传队列中删除此文件索引
if(_fileQueue.length==0)//长度0,清空数组
{
_fileQueue=null;
addChild(_selectBu);
}
var _tmp_i=0;
var _tmp_num=_imgShower.numChildren;
while(_tmp_i<_tmp_num){//重新排列剩下的图片,item索引index也要记得改变
_imgShower.getChildAt(_tmp_i).index=_tmp_i;
_imgShower.getChildAt(_tmp_i).x=10+(_tmp_i%8)*(_UIWidth/8);
_imgShower.getChildAt(_tmp_i).y=30+Math.floor(_tmp_i/8)*(_imgShowerH/2);
_tmp_i++;
}

if(_tmp_num==0){setEmptyState();}
drawImgShower(_tmp_num);
}

private function makeBody(){
//缩略图片队列容器
_imgShower=new Sprite();
_imgShower.x=2;
_imgShower.y=_headH;
addChild(_imgShower);

//大"添加图片"按钮
_selectBu=new SelectBu;
_selectBu.x=_UIWidth/2-_selectBu.width/2;
_selectBu.y=_headH+_imgShowerH/2;
_selectBu.addEventListener(MouseEvent.MOUSE_DOWN,onSelectBu);
addChild(_selectBu);
}

private function makeFoot(){
//尾部
_foot=new Sprite;
_foot.x=2;
_foot.y=_UIHeight-_footH;
addChild(_foot);
//添加底部线;
_footLine=new DotLine;
_footLine.y=55
_foot.addChild(_footLine);
//添加上传按钮
_uploadBu=new UploadBu;
_uploadBu.y=65;
_uploadBu.addEventListener(MouseEvent.MOUSE_DOWN,onUploadBu);

//添加暂停按钮
_pauseBu=new PauseBu();
_pauseBu.y=65;
_pauseBu.x=_uploadBu.width+10;
_pauseBu.addEventListener(MouseEvent.MOUSE_DOWN,onPauseBu);

//“提醒”消息显示容器
_noticeCon=new Sprite();
_noticeCon.x=300;
_noticeCon.y=0;
_foot.addChild(_noticeCon);
//addRadio();//添加单选按钮
//initTips();//初始化蓝色提示条
}

private function onSelectBu(e:Event){
_fileRefList.browse(getTypes());
}

private function onFRL(e:Event){//当文件浏览框的按钮

if(e.type==Event.SELECT)//如果是“打开”
{
var _tmp_num
var _tmp_i =0
var _tmp_file
var _tmp_list
var _tmp_hasNum
var _tmp_newH
if(!_fileQueue)//文件待上传队列为空
{    removeChild(_selectBu);
_fileQueue=clone(_fileRefList.fileList) ;//获取一个fileList副本
_tmp_num=_fileQueue.length;
if(_tmp_num>_numLimit) //选择文件数超过限制
{
notice("所加图片数超过最大限制:"+_numLimit+",只保留前"+_numLimit+"张");
_fileQueue.splice(_numLimit)    ; //截断数组只保留限制长度
}
_tmp_num=_fileQueue.length; //处理后的长度

if(Math.ceil(_tmp_num/8)>2){//超过2列
drawImgShower(_tmp_num) ;//重新绘制图片显示大框
}

while(_tmp_i<_tmp_num){  //遍历可添加的文件引用,放入_imgShower图片组显示容器
_tmp_file=new YItem(_fileQueue[_tmp_i],_upURL,sizeLimit) ;//YItem为我写的一个单个缩略图显示容器类
_tmp_file.x=5+(_tmp_i%8)*(_UIWidth/8); //坐标计算
_tmp_file.y=30+Math.floor(_tmp_i/8)*128 ;
_tmp_file.index=_tmp_i     ;
//监听小容器的各事件,分别是删除按钮被点击,整个容器按下,鼠标悬停,和移出
_tmp_file.addEventListener("delImg",onDelImg)  ;
_tmp_file.addEventListener("itemClick",onItemClic);
_tmp_file.addEventListener("itemOver",onItemOver);
_tmp_file.addEventListener("itemOut",onItemOut);
_imgShower.addChild(_tmp_file);
_tmp_i++
}
setUseState();

}//空
else{//_fileQueue不空
_tmp_list=_fileRefList.fileList  ;//接收新加入的文件
if(_fileQueue.length==_numLimit)//如果原本就满了
{
notice("图片图片队列已满("+_numLimit+"张)");
}
else {//如果原本还不满
_tmp_list=delSameFile(_tmp_list);//删掉与在显示图片组显示容器里相同的
if(_fileQueue.length+_tmp_list.length>_numLimit)//旧有+新的总长度大于64
{
_tmp_list.splice(_numLimit-_fileQueue.length) ;//把多余的扔掉
notice("图片总数超过最大限制:"+_numLimit+",只新加部分图片");
}
_tmp_num=_tmp_list.length;
if(_tmp_num) //经过检查过滤后不空
{
_tmp_hasNum=_fileQueue.length;

while(_tmp_i<_tmp_num){//加到原有的待传队列之后
_tmp_file=new YItem(_tmp_list[_tmp_i],_upURL,sizeLimit);
_tmp_file.x=5+((_tmp_i+_tmp_hasNum)%8)*(_UIWidth/8) ;
_tmp_file.y=30+Math.floor((_tmp_i+_tmp_hasNum)/8)*128;
_tmp_file.index=_tmp_i+_tmp_hasNum;
_tmp_file.addEventListener("delImg",onDelImg);
_tmp_file.addEventListener("itemClick",onItemClic);
_tmp_file.addEventListener("itemOver",onItemOver);
_tmp_file.addEventListener("itemOut",onItemOut);
_imgShower.addChild(_tmp_file);
_tmp_i++;
}
_fileQueue=_fileQueue.concat(_tmp_list);//添加到文件引用数组末端
//trace("当前文件引用:"+_fileQueue)
_tmp_num=_fileQueue.length;
if(Math.ceil(_tmp_num/8)>2){//超过2列
drawImgShower(_tmp_num)  ;//重绘图片组显示框
}
setUseState();
}
} //_fileQueue不满结束
}//_fileQueue不空结束
}

}
private function initTips(){//初始化提示条
//_tipsObj=new TipsAll
// _tipsObj.visible=false
//  _tipsObj.x=1800 //初始位置
//  _tipsObj.y=1000
//  _tipsObj.tipsText.selectable=false //动态文字不可被选择
//   addChild(_tipsObj)
//addEventListener(Event.ENTER_FRAME,moveTips) //缓冲移动  禁止丑陋的效果
}
private function moveTips(e:Event){//提示条跟随鼠标
if(!_tipsIsHide)//如果隐藏标量为fasl
{  var targetX=this.mouseX+70
var targetY=this.mouseY+70
if(stage.mouseX>512)
targetX=this.mouseX-70
if(stage.mouseY>386)
targetY=this.mouseY-70

//				   _tipsObj.x+=(targetX-_tipsObj.x)*0.1  //缓动公式
//		    _tipsObj.y+=(targetY-_tipsObj.y)*0.1
}
}

private function onItemOver(e:Event){  //鼠标悬停
//_tipsIsHide=false     //显示提示条
// _tipsObj.visible=true
var _tmp_item =e.target as YItem
// _tipsObj.tipsText.text=_tmp_item.fileR.name  //提示条文字改变
}

private function onItemOut(e:Event){ //鼠标移出
_tipsIsHide=true
//    _tipsObj.visible=false
}
private function onItemClic(e:Event){//扫描一遍图片组显示容器,将选中的图片加入批量操作数组
var _tmp_i=0
var _tmp_item
var _tmp_array=[]
while(_tmp_i<_imgShower.numChildren){
_tmp_item=YItem(_imgShower.getChildAt(_tmp_i))
if(_tmp_item.isSelected){
_tmp_array.push(_tmp_item)
}
_tmp_i++
}

_seletedItemArray=_tmp_array
}

private function onUploadBu(e:Event){//点击上传
var _tmp_i=0;
while(_tmp_i<_imgShower.numChildren){
if(YItem(_imgShower.getChildAt(_tmp_i)).checkOk())
{   notice("图片队列有错误图片,请先删除才能上传");
return;
}

_tmp_i++;
}

if(_uploadingIndex<_imgShower.numChildren){
_uploadingItem=YItem(_imgShower.getChildAt(_uploadingIndex));
_uploadingItem.addEventListener("itemSendOver",onWaitItemSend);
_uploadingItem.upload();
setUpState();
}
else{
notice("没有可上传的图片");
}
}

private function setUseState(){
//有图片时
if(!_foot.contains(_uploadBu))
_foot.addChild(_uploadBu);
if(!contains(_cleanUpBu))
addChild(_cleanUpBu);
if(!contains(_allDelBu))
addChild(_allDelBu);
if(!contains(_allRightBu))
addChild(_allRightBu);
if(!contains(_allLeftBu))
addChild(_allLeftBu);
//r1.enabled=r2.enabled=c1.enabled=c2.enabled=true;
}

private function setEmptyState(){//空图片状态时
if(_foot.contains(_uploadBu));
_foot.removeChild(_uploadBu);
if(_foot.contains(_pauseBu));
_foot.removeChild(_pauseBu);
if(contains(_cleanUpBu));
removeChild(_cleanUpBu);
if(!contains(_selectBu));
addChild(_selectBu);

if(contains(_allDelBu))
removeChild(_allDelBu);
if(contains(_allRightBu))
removeChild(_allRightBu);
if(contains(_allLeftBu))
removeChild(_allLeftBu);
//r1.enabled=r2.enabled=c1.enabled=c2.enabled=false;
}
private function setUpState(){//正在上传时
_isPause=false
if(_foot.contains(_uploadBu))
_foot.removeChild(_uploadBu);
if(!_foot.contains(_pauseBu))
_foot.addChild(_pauseBu);
if(contains(_cleanUpBu))
removeChild(_cleanUpBu);

if(contains(_allDelBu))
removeChild(_allDelBu);
if(contains(_allRightBu))
removeChild(_allRightBu);
if(contains(_allLeftBu))
removeChild(_allLeftBu);
//			r1.enabled=r2.enabled=c1.enabled=c2.enabled=false;
}
private function setUpSuccessState(){//上传成功时候的状态设置。
_isPause=false;
if(_foot.contains(_uploadBu))
_foot.removeChild(_uploadBu);
if(_foot.contains(_pauseBu))
_foot.removeChild(_pauseBu);
if(contains(_cleanUpBu))
removeChild(_cleanUpBu);

if(contains(_allDelBu))
removeChild(_allDelBu);
if(contains(_allRightBu))
removeChild(_allRightBu);
if(contains(_allLeftBu))
removeChild(_allLeftBu);
//r1.enabled=r2.enabled=c1.enabled=c2.enabled=false;
}

private function setPauseState(){//暂停时
_isPause=true
if(_foot.contains(_pauseBu))
_foot.removeChild(_pauseBu);
if(!_foot.contains(_uploadBu))
_foot.addChild(_uploadBu);
if(!contains(_cleanUpBu))
addChild(_cleanUpBu);
if(!contains(_allDelBu))
addChild(_allDelBu);
if(!contains(_allRightBu))
addChild(_allRightBu);
if(!contains(_allLeftBu))
addChild(_allLeftBu);
//r1.enabled=r2.enabled=c1.enabled=c2.enabled=true;
}
private function onWaitItemSend(e:Event){//分步一张一张上传图片。等待上一张的上传完毕
_statusTex.text="正在上传第"+_uploadingItem.index+"张图片(共"+_fileQueue.length+"张)";
_uploadingItem.alpha=0.5;
_uploadingItem.delAtOver();
_uploadingIndex=_uploadingItem.index+1;
if(!_isPause)
{
continueUpload(_uploadingIndex);
}
else{
_statusTex.text="已暂停上传...";
}
}
private function onPauseBu(e:Event){//暂停按钮
setPauseState();
}
private function continueUpload(_tmp_index){//上传下一张
if(_tmp_index<_fileQueue.length){
_uploadingItem=YItem(_imgShower.getChildAt(_tmp_index));
_uploadingItem.addEventListener("itemSendOver",onWaitItemSend);
_uploadingItem.upload();
//--调用perCallBack的js方法。
}
else{
_statusTex.text="共"+_fileQueue.length+"张图片上传完毕";
//--调用callBack函数。
this.setUpSuccessState();
ExternalInterface.call(UploadSettings.callBack,"成功上传。");
}
}

function notice(_str){ //提醒信息显示函数

var _tmp_i=0;
while(_tmp_i<_noticeCon.numChildren){//当有新消息时遍历提醒容器,将显示中的每个消息上移一个位置
if(_noticeCon.getChildAt(_tmp_i)){
_noticeCon.getChildAt(_tmp_i).y-=18;
_noticeCon.getChildAt(_tmp_i).alpha-=0.3;
}
_tmp_i++;
}
var _errorTex=new TextField(); //初始化一个新消息
var _tmp_tf=new TextFormat;
_tmp_tf.color=0xff0000;
_tmp_tf.align="center";
_errorTex.defaultTextFormat=_tmp_tf;
_errorTex.x=0;
_errorTex.y=36+20;
_errorTex.height=18;
_errorTex.width=300;
_errorTex.text="提醒:"+_str;
_noticeCon.addChild(_errorTex);
var _tmp_timer=new Timer(1000,3)//设置定时器,3次移动提示一条文本后删除该提示文本
_tmp_timer.addEventListener(TimerEvent.TIMER,function (){
//_errorTex.y-=18;  //每上移一步变透明一点
_errorTex.alpha-=0.33;
})

_tmp_timer.addEventListener(TimerEvent.TIMER_COMPLETE,function(){//3次计时后删除
if(_errorTex){
_noticeCon.removeChild(_errorTex)
_errorTex=null
}
})

_tmp_timer.start();

}

private function clone(_fArr:Array) : Array{//返回传入的数组的副本
var _tmp_i=0
var _tmp_retArr=[]
while(_tmp_i<_fArr.length){
_tmp_retArr.push(_fArr[_tmp_i])
_tmp_i++
}

return _tmp_retArr;
}
private function delSameFile(_fArr:Array) : Array //从新入图片中剔除与已在缩略图组容器内完全相同的图片并返回一个拷贝
{
var _tmp_i
var _tmp_j
var _tmp_num//新入图片长度
var _tmp_fr:FileReference;//单个新入队文件
var _tmp_isEqual:Boolean = false;//判断是否相同
var _tmp_fQNum;//已入队文件的长度
var _tmp_queuedFR:FileReference = null;//单个已入队文件
var _tmp_retArr:Array = [];
var _tmp_hasSame=false
if (_fArr)//新入队文件列
{
_tmp_i = 0;
_tmp_num = _fArr.length;
while (_tmp_i < _tmp_num)
{
_tmp_fr = _fArr[_tmp_i] as FileReference;
_tmp_isEqual = false;
_tmp_j = 0;
_tmp_fQNum = this._fileQueue.length;
while (_tmp_j < _tmp_fQNum)
{
_tmp_queuedFR = this._fileQueue[_tmp_j] as FileReference;
if (_tmp_fr.name == _tmp_queuedFR.name && _tmp_fr.type == _tmp_queuedFR.type && _tmp_fr.size == _tmp_queuedFR.size && _tmp_fr.modificationDate.time == _tmp_queuedFR.modificationDate.time && _tmp_fr.creationDate.time == _tmp_queuedFR.creationDate.time)
{   _tmp_hasSame=true
_tmp_isEqual = true;

break;
}
_tmp_j = _tmp_j + 1;
}
if (!_tmp_isEqual)
{
_tmp_retArr.push(_tmp_fr);
}
_tmp_i = _tmp_i + 1;
}
}
if(_tmp_hasSame){notice("新入图片与原图片组有重复,已删除相同图片")}
return _tmp_retArr;
}// end function

private function onDelImg(e:Event){//按下删除小按钮时
var _tmp_item=e.target as YItem
delImg(_tmp_item.index)
}
private function addRadio() { //添加2组单选按钮
/*
var cG:RadioButtonGroup=new RadioButtonGroup("allowComment");
var rG:RadioButtonGroup=new RadioButtonGroup("allowReprint");
c1 = new RadioButton();
c2 = new RadioButton();
r1 = new RadioButton();
r2 = new RadioButton();
c1.visible=false;
c2.visible=false;
r1.visible=false;
r2.visible=false;
c1.addEventListener(MouseEvent.CLICK, announceGroup);
c2.addEventListener(MouseEvent.CLICK, announceGroup);
r1.addEventListener(MouseEvent.CLICK, announceGroup);
r2.addEventListener(MouseEvent.CLICK, announceGroup);
var tf:TextFormat = new TextFormat();
tf.size=12;
StyleManager.setStyle("textFormat", tf);
c1.label="允许评论";
c2.label="禁止评论";
r1.label="允许转载";
r2.label="禁止转载";
c1.value=true;
c2.value=false;
r1.value=true;
r2.value=false;
c1.group=cG;
c2.group=cG;
r1.group=rG;
r2.group=rG;
c1.selected=true;
r1.selected=true;

c1.move(10,0);
c2.move(100,0);
r1.move(10,20);
r2.move(100,20);

_foot.addChild(c1);
_foot.addChild(c2);
_foot.addChild(r1);
_foot.addChild(r2);
*/
}

function announceGroup(e:MouseEvent):void {  //响应点选按钮事件
var rb:RadioButton=e.target as RadioButton;
if (rb.groupName=="allowComment") {
_allowComment=rb.value;
} else {
_allowReprint=rb.value;
}
}

private function drawImgShower(_tmp_num) {//根据缩略图张数重绘上传显示框大小
var _tmp_height
if(Math.ceil(_tmp_num/8)<3){//小于2行时 整个UI界面高390,上传显示框高为256
_tmp_height=_imgShowerH
_UIHeight=390-50;
if(UploadSettings.allowDesc){
_UIHeight=_UIHeight+this._descHeight*2;
}
_foot.y=_UIHeight-_footH
}
else if(Math.ceil(_tmp_num/8)>2){//大于2行时,每多一行上传框高+128,同时下部操作界面:_foot移动
_tmp_height=Math.ceil(_tmp_num/8)*(128);
_UIHeight=390+(Math.ceil(_tmp_num/8)-2)*(128)-50;
if(UploadSettings.allowDesc){
_UIHeight+=(Math.ceil(_tmp_num/8)-2)*(this._descHeight);
_tmp_height+=(Math.ceil(_tmp_num/8)-2)*(this._descHeight);
}
_foot.y=_UIHeight-_footH;
}
var _tmp_gp=this._imgShower.graphics;//绘制大框
_tmp_gp.clear();
_tmp_gp.lineStyle(1, 13684944);
_tmp_gp.beginFill(0xfffffe);
_tmp_gp.drawRect(0, 0, _UIWidth-4, _tmp_height);
_tmp_gp.endFill();
_tmp_gp.lineStyle();
_tmp_gp.beginFill(15658734);       //绘制小标题栏
_tmp_gp.drawRect(0.5, 0.5, _UIWidth-5, 22);
}

private function getTypes():Array {//返回允许类型数组
var allTypes:Array = new Array();
allTypes.push(getImageTypeFilter());
//allTypes.push(getTextTypeFilter());
return allTypes;
}

private function getImageTypeFilter():FileFilter {//FileFilter类。(1.说明文字,2允许后缀)
return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png");
}

//--设定失去焦点事件。
private function deactiveContr(e:Event){
this.stage.focus=null;
var _tmp_i=_imgShower.numChildren;
for(var i=0;i<_tmp_i;i++){
var _tmp_item=YItem(_imgShower.getChildAt(i));
_tmp_item.checkHolder();
}
}
private function obj2Boolean(obj:Object,defaultRes:Boolean){
if(obj==null){
return defaultRes;
}

var str_1:String=easis.common.StringUtils.getInstance().trim(obj.toString().toLowerCase());
if(defaultRes){
if(str_1=="false"||str_1=="0"){
return false;
}
else{
return true;
}
}
else{
if(str_1=="true"||str_1=="1"){
return true;
}
else{
return false;
}
}

}

}//class
}//pac


package {
import easis.common.StringUtils;

import fl.controls.Label;
import fl.controls.TextInput;

import flash.display.GradientType;
import flash.display.Graphics;
import flash.display.Loader;
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.events.*;
import flash.filters.BitmapFilter;
import flash.filters.BitmapFilterQuality;
import flash.filters.GlowFilter;
import flash.geom.Matrix;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.FileReferenceList;
import flash.net.URLRequest;
import flash.system.Security;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.external.ExternalInterface;

/*   presented by yukon12345  (http://hi.baidu.com/yukon_kanzaki/blog/item/b500fd1f77d808f8e1fe0b88.html)
/*
/*   generate from BAIDU
/*   注意:软件遵循MIT使用许可协议(http://zh.wikipedia.org/zh-cn/MIT许可证)
/*   可自由转载,修改和用于商业用途,但使用时必须保留此注释段所有信息 2010-6-14
*/
public class YItem extends Sprite {
private var _statusTex:TextField;         //状态提示文本
private var _loader;                    //缩略图载入器
private var _urlRequest;              //上传的URLRquest实例
private var _cSize:uint=95;            //整个缩略图显示框大小
private var _size:uint=85;            //整个缩略图大小
private var container;
private var okIcon;                    //上传完成标志小图标
private var delIcon;                   //删除小图标
public var index                      //在图片组容器里的索引值

private var description_height:uint=20;//输入框的高度
private var leftIcon                //左旋图标
private var rightIcon               //右旋图标
private var loadOver=false    		//读入内存完毕
private var r:Sprite   			 //帮助旋转的父容器
private var sizeLimit=2*1024*1024 //2M上传限制
private var typeError=false     //是否后缀错误
private var sizeError=false    //是否0字节或者超过允许大小
private var codeError=false    //是否编码错误(非允许图片格式编码)
private var loadingBar:Sprite
private var isUploading=false  //是否在上传中
public  var filterArray =new Array(".gif",".jpg",".jpeg",".png") //默认允许的后缀
public  var uploadOver=false  //上传发送完毕
public  var fileR  :FileReference          //缩略图的文件引用
private var  _border:Sprite;  //被选中框
public var isSelected         //被选中标量
private var desc_area:Sprite=new Sprite();//描述用输入框区域。
public var text_desc:TextField=new TextField();//描述输入框
private var text_holder:TextField =new TextField();//输入框的提示文字。
private var _allowDesc:Boolean=false;

public function allowInputDesc(trueOrFalse:Boolean):Boolean{
this.desc_area.visible=trueOrFalse;
return true;
}

public function YItem(_fr,_upURL="up.php",_sizeLimit=2*1024*1024) {
this._allowDesc=UploadSettings.allowDesc;
sizeLimit=_sizeLimit
fileR=_fr as FileReference;
//fileR.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA

_urlRequest=new URLRequest();
_urlRequest.url=UploadSettings.uploadUrl;//_upURL;//文件上传路径
_border=new Sprite //绿色的被选中框
_border.graphics.lineStyle(3, 0x00ff00);
_border.graphics.moveTo(0,0);
var _border_y:uint=this._cSize;
if(this._allowDesc){
_border_y=this._cSize+this.description_height;
}

_border.graphics.lineTo(0,_border_y);

_border.graphics.lineTo(_cSize,_border_y);
_border.graphics.lineTo(_cSize,0);
_border.graphics.lineTo(0,0);
_border.alpha=0
addChild(_border);

container=new Sprite();//容器。用来装载一个图片预览用的各种东西.
//画一条灰色小边框。并用渐变填充。让它更像百度上传界面。具体不用深究
container.graphics.lineStyle(1, 0xb4b4b4);
container.graphics.moveTo(4,4);
container.graphics.lineTo(4,_cSize-4);
container.graphics.lineTo(_cSize-4,_cSize-4);
container.graphics.lineTo(_cSize-4,4);
container.graphics.lineTo(4,4);
container.graphics.lineStyle();
var matrix:* = new Matrix();//变换矩阵
matrix.createGradientBox(_size, _size, 2 * Math.PI / 5);
//渐变填充
container.graphics.beginGradientFill(GradientType.LINEAR, [15198183, 16777215], [0.8, 0], [0, 250], matrix);
container.graphics.drawRect(4, 4, _size+3, _size);
container.graphics.endFill();
container.addEventListener(MouseEvent.ROLL_OVER,onOverCon)  //侦听移入。移入时显示左右旋转和删除按钮,还有绿色的选中框
container.addEventListener(MouseEvent.ROLL_OUT,onOutCon)   //侦听移出。移出不显示那些按钮
container.addEventListener(MouseEvent.MOUSE_DOWN,onDownCon) //侦听鼠标点击。点击后显示选择框。并设置被选中标志isSelected。
addChild(container);

_statusTex=new TextField();//状态输出文本域
_statusTex.x=10;
_statusTex.y=_cSize-30;
_statusTex.width=80;
_statusTex.height=18;
_statusTex.selectable=false
var _tmp_tf=new TextFormat    //字体格式
_tmp_tf.color=0xffffff;
var _tmp_gf =new GlowFilter(0xFF002F)  //发光滤镜
var _tmp_filterA =new Array(_tmp_gf);
_statusTex.filters=_tmp_filterA
_statusTex.defaultTextFormat=_tmp_tf
container.addChild(_statusTex);

okIcon=new UpOkIcon  ;//上传成功小箭头
okIcon.x=80;
okIcon.y=80

delIcon=new DelIcon  ;//删除小叉叉
delIcon.x=73;
delIcon.y=10;
delIcon.addEventListener(MouseEvent.MOUSE_DOWN,onDelIcon);//侦听删除

leftIcon=new SmallLeft
leftIcon.x=10
leftIcon.y=10
leftIcon.addEventListener(MouseEvent.MOUSE_DOWN,function(){//侦听左旋小按钮
r.rotation-=90
});

rightIcon=new SmallRight
rightIcon.x=50
rightIcon.y=10
rightIcon.addEventListener(MouseEvent.MOUSE_DOWN,function(){//侦听右旋
r.rotation+=90
});
handleFileR();//初始化一个文件引用

_loader=new Loader();//loader容器。用来获取图片预览
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);//侦听载入数据完成
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,function(){//检查文件编码。非图像编码显示错误
loadOver=true  //跳过读取
codeError=true //编码错误
_statusTex.text="文件编码错误";
})
r=new Sprite   //旋转容器,方便旋转
r.x=_cSize/2
r.y=_cSize/2
r.addChild(_loader)
container.addChildAt(r,0);

loadingBar=new Sprite    //loading条
loadingBar.graphics.beginFill(0x3FEB8D);
loadingBar.graphics.drawRect(0, _cSize, _cSize, 3);
loadingBar.graphics.endFill();
loadingBar.scaleX=0     //先长度为0%
container.addChild(loadingBar)
//--加入图片描述框
//this.container.addChild(this.text_desc);
//this.text_desc.visible=false;
//this.text_desc.text="请输入描述文字";
this.initDescInput();
//this.allowInputDesc(false);
}

public function initDescInput(){
this.addChild(this.desc_area);
this.desc_area.x=0;
this.desc_area.y=this._cSize-3;
this.text_desc.type=flash.text.TextFieldType.INPUT;
this.text_desc.autoSize=flash.text.TextFieldAutoSize.NONE;
//设置描述框区域的边框,使其看上去像百度的。
this.desc_area.graphics.lineStyle(1, 0xb4b4b4);
this.desc_area.graphics.moveTo(4,0);
this.desc_area.graphics.lineTo(4,this.description_height);
this.desc_area.graphics.lineTo(_cSize-4,this.description_height);
this.desc_area.graphics.lineTo(_cSize-4,0);
//this.desc_area.graphics.lineTo(4,0);
this.desc_area.graphics.lineStyle();
//设定字体颜色
this.text_desc.textColor=0xfB4B4B4;
this.text_desc.y=0;
this.text_desc.x=4;
//边框
//this.text_desc.border=true;
//this.text_desc.borderColor=0xA7A6A4;
this.text_desc.width=this._cSize-8;

//画线,明确输入框位置。
//text的具体设置
var tf:TextFormat = this.text_desc.getTextFormat();
tf.letterSpacing = 2;//字符间距
tf.color=0xfB4B4B4;
tf.size=14;

this.text_desc.defaultTextFormat=tf;
//this.desc_area.addChild(this.text_holder);
this.desc_area.addChild(this.text_desc);
//this.text_desc.text="选择。";
//this.text_desc.
//--设定text_holder
var tf_holder:TextFormat = this.text_holder.getTextFormat();
tf_holder.letterSpacing = 0;//字符间距
tf_holder.color=0xfB4B4B4;
tf_holder.size=12;
this.text_holder.autoSize=flash.text.TextFieldAutoSize.CENTER;
this.text_holder.defaultTextFormat=tf_holder;
this.desc_area.addChild(this.text_holder);
this.text_holder.text="请输入描述";
this.text_holder.addEventListener(MouseEvent.CLICK,this.initHolderClick);
this.text_desc.addEventListener(MouseEvent.CLICK,function(ev:Event){
ev.stopPropagation();});
this.text_desc.addEventListener(Event.DEACTIVATE,this.initTextDescDeactive);
}
//--设定点击holder时候隐藏holder并且focus描述输入框。
private function initHolderClick(ev:Event){
this.text_holder.visible=false;
this.text_desc.visible=true;
this.text_desc.stage.focus=this.text_desc;
ev.stopPropagation();
}
public function checkHolder(){
if(easis.common.StringUtils.getInstance().isEmpty( this.text_desc.text)){
this.text_desc.visible=false;
this.text_holder.visible=true;
}
}
//失去焦点时候,判断是不是没有填写任何信息。
private function initTextDescDeactive(ev:Event){
if(easis.common.StringUtils.getInstance().isEmpty( this.text_desc.text)){
this.text_desc.visible=false;
this.text_holder.visible=true;
}
}

public function delAtOver(){  //上传完毕后删除对缩略图的移入移出侦听
container.removeEventListener(MouseEvent.ROLL_OVER,onOverCon);
container.removeEventListener(MouseEvent.ROLL_OUT,onOutCon);
}

private  function onOutCon(e:Event){//鼠标移到缩略图上将显示操作菜单
if(loadOver){ //载入内存完毕,加入缩略图上的操作按钮,左右旋转和删除按钮
if(container.contains(delIcon))
container.removeChild(delIcon)
if(container.contains(rightIcon))
container.removeChild(rightIcon)
if(container.contains(leftIcon))
container.removeChild(leftIcon)
dispatchEvent(new Event("itemOut"))
if(_border.alpha==0.5&&!uploadOver)
{_border.alpha=0}
}
}

private function onDownCon(e:Event) {//鼠标点击
if((!uploadOver)&&loadOver){
if(!(e.target as SmallLeft)&&(!(e.target as SmallRight))){//如果不是左右旋转按钮
switch(_border.alpha)//判断点击前的边框alpha来执行相应操作,标示是否选择
{
case 1:
_border.alpha=0
isSelected=false
break;
case 0:
_border.alpha=1
isSelected=true
break;
case 0.5:
_border.alpha=1
isSelected=true
break;
default:
//trace("what wrong")
break;
}//switch

//trace(isSelected)
dispatchEvent(new Event("itemClick"))  //分发事件通知图片组容器
}//if2
}//if1
}

private function onOverCon(e:Event){//鼠标移到缩略图上将显示操作菜单
if(loadOver){//如果载入完毕
container.addChild(delIcon)
container.addChild(rightIcon)
container.addChild(leftIcon)
dispatchEvent(new Event("itemOver"))
if(_border.alpha==0&&!uploadOver){
_border.alpha=0.5;
}
}//if
}//f

public function turnLeft(){//公共函数 缩略图左旋
r.rotation-=90
}
public function turnRight(){//公共函数 缩略图右旋
r.rotation+=90
}//f

private function handleFileR() {//FileReference为单个文件引用类。用来处理单个文件这里为了简单而使用。

fileR.addEventListener(Event.COMPLETE, onFileExecute);//fileR.load()载入内存完毕
fileR.addEventListener(Event.OPEN, onFileExecute);//打开待上传
fileR.addEventListener(ProgressEvent.PROGRESS, onFileExecute);//上传中事件
fileR.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onFileExecute);//上传完毕事件
fileR.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onFileExecute);//安全错误
fileR.addEventListener(IOErrorEvent.IO_ERROR, onFileExecute);//io错误。一般是上传地址
fileR.addEventListener(HTTPStatusEvent.HTTP_STATUS, onFileExecute);//监听服务器返回状态
if(fileR.size==0 || fileR.size>sizeLimit){//检查文件大小。0字节或者超过大小不载入
loadOver=true
sizeError=true
_statusTex.text="文件大小错误";
return
}
if(filterArray.indexOf(fileR.type)==-1)//检查文件格式后缀名
{
loadOver=true
typeError=true
_statusTex.text="文件格式错误";
typeError=true
}
//_statusTex.text="载入预览图..";
fileR.load();//开始读取图片数据到内存
}//f

private function onDelIcon(e:Event) {//点击删除小叉后发出事件,通知容器删除
dispatchEvent(new Event("delImg"))
}//f

private function onLoaded(e:Event) {//调整缩略图大小和位置
var w=_loader.width;
var h=_loader.height;
var scalePercent:Number=w/h;
if (w>h) {
_loader.width=_size;
_loader.height=_size/scalePercent;
} else if (h>w) {
_loader.height=_size;
_loader.width=_size*scalePercent;
} else {
_loader.height=_loader.width=_size;
}
_loader.x=-_loader.width/2;
_loader.y=-_loader.height/2
}

public function upload() {//上传
isUploading=true
fileR.upload(_urlRequest);//执行上传
}//function

public function checkOk(){//公共函数 检测是否有错误,返回true为有错误,false无错误
if(sizeError){
_statusTex.text="文件大小错误";
return true
}
if(typeError){
_statusTex.text="文件类型错误";
return true
}
if(codeError){
_statusTex.text="文件编码错误";
return true
}
return false
}//function

private function onFileExecute(e:Event) {//文件相关事件处理
switch (e.type) {
case Event.COMPLETE :            //载入完成
//遇到载入错误(非图片编码格式),直接跳过载入
if(checkOk()){trace("!!");loadOver=true;return}
_loader.loadBytes(fileR.data);
//_statusTex.text="";
loadOver=true;
break;

case Event.OPEN :
//遇到打开错误,(0字节)直接跳过载入内存
if(checkOk()){trace("打开错误");loadOver=true;return}
break;

case ProgressEvent.PROGRESS :    //载入或者上传中
//_statusTex.text="处理中.."
if(checkOk()){return}

if(isUploading){//如果是上传
var persent=ProgressEvent(e).bytesLoaded/ProgressEvent(e).bytesTotal;
loadingBar.scaleX=persent
}
break;

case DataEvent.UPLOAD_COMPLETE_DATA ://发送完成

if(checkOk()){_statusTex.text="文件错误!";return;}
//_statusTex.text="发送完毕!";
container.addChild(okIcon);
//--在这里调用回调函数吧。
var devent:DataEvent= e as DataEvent;
trace("服务端返回数据:"+devent.data);
uploadOver=true;
try{
ExternalInterface.call(UploadSettings.perCallBack,devent.data);
}
catch(ee){
this._statusTex.text=ee;
}
dispatchEvent(new Event("itemSendOver"));
break;

case SecurityErrorEvent.SECURITY_ERROR :
_statusTex.text="安全设置错误!";
uploadOver=true
dispatchEvent(new Event("itemSendOver"))
break;

case IOErrorEvent.IO_ERROR :
_statusTex.text="网络或文件错误";
uploadOver=true
dispatchEvent(new Event("itemSendOver"))
break;

case HTTPStatusEvent.HTTP_STATUS :
if (e.target.status==200) {
_statusTex.text="服务器成功处理!";

} else {

_statusTex.text="服务器处理失败!";
}
break;

default :
_statusTex.text="未知事件";
break;
}//switch
}//function

}//class
}//pac


package
{
public class UploadSettings
{
public static var uploadUrl:String="";//上传图片的后台处理地址。
public static var max:int=8;//最大上传图片张数。
public static var allowDesc:Boolean=true;
public static var perCallBack:String="alert";//js回调函数,请注意,这是其中一个图片上传完以后会调用的函数。注意区分。传进去的是服务端返回的字符串,需要自行处理字符串。
public static var callBack:String="alert";//js回调函数。请注意,这是所有图片都上传完毕以后回调的函数,注意,这个方法是调用完毕后才回调的,没有参数。
public static var sequenceKey:String="sequence";//发送文件时候,flash会向后台发送一个标识当前图片次序的参数,这个参数的key可以定制,默认为sequence,但是你也可以修改成为其他。
}
}


html调用页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<script type="text/javascript" src="/static/lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/static/lib/jquery.cookie.min.js"></script>
<script type="text/javascript" src="/static/lib/util.min.js"></script>
<script type="text/javascript" src="/static/lib/jquery.bgiframe.min.js"></script>
<script type="text/javascript" src="/static/lib/jshashtable.min.js"></script>
<!--弹出窗口插件-->
<link rel="stylesheet" href="/static/UI/artdialog/skins/phpcmsDialog.css" />
<script type="text/javascript"  src="/static/UI/artdialog/artDialog.js"></script>
<script type="text/javascript"  src="/static/UI/artdialog/plugins/iframeTools.js"></script>
<script type="text/javascript"  src="/static/UI/artdialog/artDialog.ex.js"></script>
<script type="text/javascript" src="/static/UI/imgBox/imgPreviewBox.js"></script>

<script type="text/javascript" src="/static/lib/swfobject.js"></script>
</head>
<body>
<h3>测试图片批量上传</h3>
<input type="button" value="点击我开始批量上传" id="btn_upload"/>
<h3>上传图片结果</h3>
<div id="showImg"></div>
<script type="text/javascript">
var __totalCount=0;//图片计数器,计算总共多少图片
var __totalSuccess=0;//计算总共多少图片成功上传。
var __totalFailed=0;//计算总共多少图片上传失败。
var _currentDialog=null;
$(document).ready(function(){
$("#btn_upload").click(function(){
__totalCount=0;
__totalFailed=0;
__totalSuccess=0;
$("#showImg").html("");
_currentDialog=  art.dialog({
title:"批量上传【demo】",
content:"<div style=' position: relative; width:850px;height:450px;' ><div style='width:1200px;height:450px; position: absolute; left:-350px;'><div id='content1' style='width:1400px;height:450px;'></div></div></div>",
init:function(){
initUploadComponent();
}

});
});
});

function perCallBack(jsonDataString){
try{
var jsonData= $.parseJSON(jsonDataString);
}
catch (ed){
console.log(ed);
return;
}
__totalCount++;
if(jsonData["status"]==true){
__totalSuccess++;
}
else{
__totalFailed++;
}

var status=jsonData["status"];
var message=jsonData["message"];
if(status==false){
if(_currentDialog!=null){
_currentDialog.close();
}
alert(message);
return;
}
//否则就添加相关图片进去。
var _html1="<div style='margin-top:10px;' id='viewimg_"+__totalCount+"'><div>";
alert(jsonDataString);
var _vitem=$(_html1);
$("#showImg").append(_vitem);
new imgPreviewBox({
id:"previewbox_"+__totalCount, //这个预览框的id,请保持唯一
container:_vitem,//这个是预览框需要加入到的container的元素
boxwidth:200,//这个box的宽度
boxheight:200,//这个box的高度
imgurl:jsonData["url"],//这个box需要加载图片的高度
init:function(previewElement){
$(previewElement).css("background-color","#4d4d4d");
$(previewElement).css("border","1px");
}          ,
loadFail:function(){
alert("加载失败!");
}
});

}
function callBack(){
if(_currentDialog!=null){
_currentDialog.close();
}
alert("工作完毕。");
}

function initUploadComponent(){
var flashvars = {
uploadUrl:"/quickTest/YUploadHandler.jsp",//上传图片的后台处理地址。
max:8,//最大上传图片张数。
allowDesc:true,//是否运行编辑图片描述
perCallBack:"perCallBack",//js回调函数,请注意,这是其中一个图片上传完以后会调用的函数。注意区分。传进去的是服务端返回的字符串,需要自行处理字符串。
callBack:"callBack",//js回调函数。请注意,这是所有图片都上传完毕以后回调的函数,注意,这个方法是调用完毕后才回调的,没有参数。
sequenceKey:"sequence"//发送文件时候,flash会向后台发送一个标识当前图片次序的参数,这个参数的key可以定制,默认为sequence,但是你也可以修改成为其他。
};

var params = {
menu: "false",
scale: "noScale",
allowFullscreen: "true",
allowScriptAccess: "always",
wmode:"transparent",
bgcolor: "#FFFFFF"
};

var attributes = {
id:"FaustCplus"
};
//swfobject.embedSWF("/static/UI/avatar/FaustCplus.swf", "altContent", "800", "500", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
// swfobject.embedSWF("/static/UI/avatar/FaulstCplusAS.swf", "altContent", "800", "500", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
swfobject.embedSWF("/static/UI/YUpload/YUploadImg.swf", "content1", "1200", "450", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}
</script>
</body>
</html>


jsp处理页面:

<%@ page import="java.util.Hashtable" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.FileUploadException" %>
<%@ page import="java.io.FileOutputStream" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%!
/**
* 在servlet或者jsp里面获取当前web的根目录绝对路径譬如:F:/projects/myCMS/这种形式。
* */
public static String getRealPath(HttpServletRequest request,String path){
String servletPath = request.getServletPath();
String realPath = request.getSession().getServletContext()
.getRealPath(servletPath);
String WebRootPath=realPath.replace('\\','/');
WebRootPath=WebRootPath.substring(0,WebRootPath.lastIndexOf(servletPath));
WebRootPath=(WebRootPath+"/"+path).replaceAll("//","/").replace('/','\\');
return      WebRootPath;
}%>
<%
Hashtable<String,Object> _hash=new Hashtable<String, Object>(3);
String _avatarRoot="/__test/yupload";
String savePath = getRealPath(request, _avatarRoot);
File f_d=new File(savePath);
if(!f_d.exists()){
f_d.mkdirs();
}

//--接收图片
//--接收图片开始
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
FileItem _fileItem=null;
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
//  System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {

_fileItem=item;
}else{
}
}
}
if(_fileItem==null){
_hash.put("status",false);
_hash.put("message","没有上传任何文件!");
_hash.put("url","");
out.write(JSON.toJSONString(_hash));
return;
}
String fileNameExt=_fileItem.getName().trim();// new String(_fileItem.getName().getBytes("gbk")).trim();
fileNameExt=fileNameExt.substring(fileNameExt.lastIndexOf('.')+1);
System.out.println(fileNameExt);
String fileName_2=request.getSession().getId()+((new Date()).getTime());
String _newFileName=fileName_2+"."+fileNameExt;
String realFilePath=savePath+File.separator+_newFileName;
String realURL=_avatarRoot+"/"+_newFileName;
//--写入文件
File f1=new File(realFilePath);
if(f1.exists()){
f1.delete();
}
_fileItem.write(f1);
_hash.put("status",true);
_hash.put("message","成功上传图片!");
_hash.put("url",realURL);
out.write(JSON.toJSONString(_hash));
}catch(FileUploadException e){

e.printStackTrace();
_hash.put("status",false);
_hash.put("message","上传文件失败,文件流异常!");
_hash.put("url","");
out.write(JSON.toJSONString(_hash));
return;
} catch (Exception e) {
e.printStackTrace();
_hash.put("status",false);
_hash.put("message","服务器500错误!");
_hash.put("url","");
out.write(JSON.toJSONString(_hash));
return;
}
//--接收图片结束
%>


效果:

点击上传按钮:



添加图片:



上传图片:



嗯,数量不对,有bug。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: