dadamoney

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

最近在做大文件上传项目时碰到了很多问题。基于.net的大文件上传组件网上是大把的有。


大家可去查询:http://www.baidu.com/s?lm=0&si=&rn=10&ie=gb2312&ct=0&wd=asp%2Enet+%B4%F3%CE%C4%BC%FE%C9%CF%B4%AB&pn=0&ver=0&cl=3&uim=1&usm=0&f=1

这些组件基本上都是基于HttpModule模式的,大部分都存在一个致命的问题:严重消耗内存。

最后没办法,只好采用Flash的FileReference模式去上传。具体我也不是很明白,大家可自己研究。

一、CS相应源码如下:


import flash.net.FileReference;
import flash.net.URLRequest;
import flash.net.FileFilter;
import flash.display.Sprite;
import flash.events.
*;



var fileRef 
= new FileReference();
var fileListener 
= new Object();

var totalBytes:Number 
= 0;
var uploadedBytes:Number 
= 0;

//从外部获取也许上传的文件类型
var acceptFileType:String = getFlashVars("acceptFileType");
//设置上传完毕后执行的js脚本
var comJsFun:String=getFlashVars("ComJsFun");
//this.tbFilePath.text = comJsFun;
//
var uploadURL:URLRequest = new URLRequest();
var xmlRequest:URLRequest 
= new URLRequest();
var xmlLoader:URLLoader 
= new URLLoader();

//初始化系统
function init() {
    
this.mcWaterStyle.visible = false;
    
this.mcFilePlayer.visible = false;
    
this.progressBar.visible = false;

    
//设置按钮文字大小,默认的字体和大小有点难看。
    var myFormat = new TextFormat();
    myFormat.size 
= 12;
    
this.btBrowser.setStyle("textFormat", myFormat);
    
this.btUpload.setStyle("textFormat", myFormat);
    
this.tbFilePath.setStyle("textFormat", myFormat);
    
    
this.mcWaterStyle.style0.setStyle("textFormat", myFormat);
    
this.mcWaterStyle.style1.setStyle("textFormat", myFormat);
    
this.mcWaterStyle.style2.setStyle("textFormat", myFormat);
    
this.uploadInfo.setStyle("textFormat", myFormat);
    
//如果从FlashVars获取的参数acceptFileType(限定上传文件类型)无值,那么访问相应的XML(上传文件类型配置)
    if(acceptFileType==""){
        
//从外部获取上传附加的文件类型。
        xmlRequest = new URLRequest("http://www.cnblogs.com/XML/Setting_Article.xml");
        xmlLoader.load(xmlRequest); 
        xmlLoader.addEventListener(Event.COMPLETE,loaderHandler);
    }

}


init();

//按钮事件
this.btBrowser.addEventListener(MouseEvent.CLICK, browseHandler);
this.btUpload.addEventListener(MouseEvent.CLICK, UploadHandler);

fileRef.addEventListener(Event.SELECT,selectHandler);
//选择文件
fileRef.addEventListener(Event.CANCEL, cancelHandler);//上传过程中取消事件
fileRef.addEventListener(Event.OPEN, openHandler);//开始上传事件
fileRef.addEventListener(Event.COMPLETE, completeHandler);//上传完毕事件
fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler)//上传数据完毕事件,有点迷惑Event.COMPLETE跟DataEvent.UPLOAD_COMPLETE_DATA的区别
fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);//上传过程事件,相应的进度条代码在这里了

//监听上传过程可能出错的事件
fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);


//浏览按钮事件
function browseHandler(event:MouseEvent):void {
    fileRef.browse(browseGetTypes());
}

function browseGetTypes():Array 
{
    var allTypes:Array 
= new Array(browseGetFileTypeFilter());
    
return allTypes;
}


function browseGetFileTypeFilter():FileFilter 
{
    
    
if(acceptFileType!=""){
        var arr 
= acceptFileType.split("|");
        var FileExtension 
= "";
        
for(var i=0;i<arr.length;i++){
            
if (arr[i] == ""
                 
continue;
            
if(i==0)
                FileExtension 
= "*."+arr[i];
            
else
                FileExtension 
= FileExtension+";*."+arr[i];
        }

        
return new FileFilter("文件格式("+FileExtension+")"""+FileExtension+"");
    }
else{
        
return new FileFilter("所有文件(*.*)","*.*");
    }

    
    
//return new FileFilter("所有文件(*.*)","*.*");
}


//加载上传配置事件
function loaderHandler(event:Event):void {
    var myXML:XML 
= new XML(xmlLoader.data); 
    
//myXML = XML();
    acceptFileType = myXML.child("Upload").ContontFileStyle;
    trace(
"--"+myXML.child("Upload").ContontFileStyle+"--");
    
if(this.uploadInfo.text=="")
        
this.uploadInfo.text = "允许的格式:"+myXML.child("Upload").ContontFileStyle;
}


//选择文件事件
function selectHandler(event:Event):void{
     
this.uploadInfo.text = "";
     
this.mcWaterStyle.visible = false;
     
this.mcFilePlayer.visible = false;
     
     
if (fileRef.size > 0){
         totalBytes 
= fileRef.size;
         
this.tbFilePath.text =  fileRef.name+ "[" + this.getSizeType(totalBytes) + "]";
         var fileExtName 
= fileRef.name.substring(fileRef.name.lastIndexOf(".")+1);
         
switch(fileExtName.toLowerCase()){
             
case "jpg":
             
case "jpeg":
             
case "gif":
             
case "bmp":
                 
this.mcWaterStyle.visible = true;
                 
break;
             
case "flv":
                 
this.mcFilePlayer.visible = true;
                 
this.mcFilePlayer.mcWidth.text = 410;
                 
this.mcFilePlayer.mcHeight.text = 370;
                 
break;
             
case "swf":
                 
this.mcFilePlayer.visible = true;
                 
this.mcFilePlayer.mcWidth.text = 550;
                 
this.mcFilePlayer.mcHeight.text = 400;
                 
break;
             
case "rm":
             
case "rmvb":
             
case "mp3":
             
case "avi":
             
case "mpg":
             
case "mpeg":
             
case "asf":
             
case "wmv":
             
case "wma":
                 
this.mcFilePlayer.visible = true;
                 
this.mcFilePlayer.mcWidth.text = 550;
                 
this.mcFilePlayer.mcHeight.text = 400;
                 
break;
             
default:
                 
this.mcWaterStyle.visible = false;
                 
this.mcFilePlayer.visible = false;
                 
break;
         }

    }
else{
         
this.uploadInfo.text = "错误:您没有选择文件!";
    }
 
}


//上传过程中取消
function cancelHandler(event:Event):void{
    
this.progressBar.visible = false;
}
;

//当上载或下载操作开始时
function openHandler(event:Event):void{
    
this.tbFilePath.visible = false;
    
this.mcWaterStyle.visible = false;
    
this.mcFilePlayer.visible = false;
    
this.btBrowser.visible = false;
    
this.btUpload.label = "取消";
    
this.progressBar.visible = true;
}
;

//点击伤
function UploadHandler(event:MouseEvent):void{
    
if (this.btUpload.label=="上传"){
        var WaterMarkStyleP:String 
= "";
        
if(this.mcWaterStyle.style0.selected == true)
            WaterMarkStyleP 
= "0";
        
else if(this.mcWaterStyle.style1.selected == true)
            WaterMarkStyleP 
= "1";
        
else if(this.mcWaterStyle.style2.selected == true)
            WaterMarkStyleP 
= "2";
        
        var mcFilePlayerP:String
="&width="+this.mcFilePlayer.mcWidth;
        mcFilePlayerP 
+= "&height="+this.mcFilePlayer.mcHeigth;
        
        
if(this.mcFilePlayer.mcAutoYes.selected == true)
            mcFilePlayerP 
+= "&auto=true";
        
else if(this.mcFilePlayer.mcAutoNo.selected == true)
            mcFilePlayerP 
+= "&auto=false";
            
        uploadURL.url
="Upload_File_SWF.aspx?WaterMarkStyle="+WaterMarkStyleP+mcFilePlayerP;
        fileRef.upload(uploadURL);
//此为采用aspx默认方式进行上传的文件地址。如:Upload_File_SWF.aspx此页面我在上传完毕后,直接进行Response.Write("true");那么Flash可在uploadCompleteDataHandler后可后去到true这个数据。以便你进行操作。
    }
else if(this.btUpload.label=="取消"){
        
this.tbFilePath.visible = true;
        
this.mcWaterStyle.visible = false;
        
this.mcFilePlayer.visible = false;
        
this.btBrowser.visible = true;
        
this.btUpload.label = "上传";
        
this.progressBar.visible = false;
        
this.uploadInfo.text="";
    }
else if(this.btUpload.label=="重新上传"){
        
this.tbFilePath.visible = true;
        
this.mcWaterStyle.visible = false;
        
this.mcFilePlayer.visible = false;
        
this.btBrowser.visible = true;
        
this.btUpload.label = "上传";
        
this.progressBar.visible = false;
    }

}


//在文件上载或下载操作期间定期调用
function progressHandler(event:ProgressEvent):void{
    
//var fileRef:FileReference = FileReference(event.target);
    if(event.bytesLoaded==event.bytesTotal){
        
this.uploadInfo.text= "正在转移数据,请稍后--"+getSizeType(event.bytesLoaded)+"/"+getSizeType(event.bytesTotal);
    }
else{
        
this.progressBar.mcMask.width = (event.bytesLoaded/event.bytesTotal)*this.progressBar.mcLoaded.width;
        
this.uploadInfo.text="上传文件中,请等待--"+getSizeType(event.bytesLoaded)+"/"+getSizeType(event.bytesTotal);
    }

}


function completeHandler(
event:Event):void {
    
//trace("completeHandler: " + event);
    this.tbFilePath.visible = true;
    
this.tbFilePath.text = "";
    
this.mcWaterStyle.visible = false;
    
this.mcFilePlayer.visible = false;
    
this.btBrowser.visible = true;
    
this.btUpload.label = "上传";
    
this.progressBar.visible = false;
    
//this.uploadInfo.text = "上传成功!";
}


function uploadCompleteDataHandler(
event:DataEvent):void {
    
if(event.data.indexOf("|")!=-1){
        var fileInfoArr 
= event.data.split("|");
        
if(fileInfoArr[0].toLowerCase()=="true"){
            
this.uploadInfo.text = "上传成功:"+fileInfoArr[1]+"";
            
if(comJsFun!=""){
                
//ExternalInterface.call("UploadForEditor","hh");
                ExternalInterface.call("UploadForEditor",event.data.replace("true|",""));
                
//this.tbFilePath.text = event.data;
            }

        }
else{
            
this.uploadInfo.text = "上传失败:"+EncodeUtf8(fileInfoArr[1])+"";
        }

    }

    
    
    
    trace(
"uploadCompleteData: " + event.data);
}




//错误事件
function httpStatusHandler(event:HTTPStatusEvent):void {
   trace(
"httpStatusHandler: " + event);
   
this.mcWaterStyle.visible = false;
   
this.mcFilePlayer.visible = false;
   
this.uploadInfo.text="HTTP错误: " +  event;
}

function ioErrorHandler(
event:IOErrorEvent):void {
   trace(
"ioErrorHandler: " + event);
   
this.mcWaterStyle.visible = false;
   
this.mcFilePlayer.visible = false;
   
this.uploadInfo.text="IO错误: " +  event;
}

function securityErrorHandler(
event:SecurityErrorEvent):void {
   trace(
"openHandler: " + event);
   
this.mcWaterStyle.visible = false;
   
this.mcFilePlayer.visible = false;
   
this.uploadInfo.text="IO安全设置错误: " +  event;
}








/*--------------------以下为常用函数-------------
---------------------------------------------
*/

//处理文件大小表示方法
function getSizeType(s)
{
    var danwei 
= ["Byte","KB","MB","GB" ];
    var d 
= 0;
    
while ( s >= 900 )
    
{
        s 
= Math.round(s*100/1024)/100;
        d
++;
    }

    
return s+danwei[d];
}


function getFlashVars(parName)
{
    var parValue:String
=stage.loaderInfo.parameters[parName];
    
if(parValue==null)
       
return "";
    
else
       
return parValue;
}




//转换乱码
function EncodeUtf8(str : String):String {
    var oriByteArr : ByteArray 
= new ByteArray();
    oriByteArr.writeUTFBytes(str);
    var tempByteArr : ByteArray 
= new ByteArray();
    
for (var i = 0; i<oriByteArr.length; i++{
        
if (oriByteArr[i] == 194{
            tempByteArr.writeByte(oriByteArr[i
+1]);
            i
++;
        }
 else if (oriByteArr[i] == 195{
            tempByteArr.writeByte(oriByteArr[i
+1+ 64);
            i
++;
        }
 else {
            tempByteArr.writeByte(oriByteArr[i]);
        }

    }

    tempByteArr.position 
= 0;
    
return tempByteArr.readMultiByte(tempByteArr.bytesAvailable,"chinese");
    
//return tempByteArr.readMultiByte(tempByteArr.bytesAvailable,"chinese");
}

二、相应的上传文件代码(.net)


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;


namespace TT.WebManager.Web.Admin.Article
{
    
public partial class Upload_File_SWF : System.Web.UI.Page
    
{
        
string AppPath = "";

        
string FileURL = "";//文件网络地址
        string FileURL2 = "";//文件网络地址,如果加了水印
        string FileAppPath = "";
        
string FileAppPath2 = "";

        
string sFilePathName = "";
        
string sFileName = "";
        
int FileSize = 0;

        
string FileExtName = "";

        
int WaterMarkStyle = 0;
        
string FileAuto = "true";
        
int FileWidth = 0;
        
int FileHeigth = 0;

        
protected void Page_Load(object sender, EventArgs e)
        
{
            TT.WebManager.BLL.Setting bll 
= new TT.WebManager.BLL.Setting();
            bll.Init(
false);

            AppPath 
= System.Web.HttpContext.Current.Request.PhysicalApplicationPath;

            WaterMarkStyle 
= Methods.Req.GetInt("WaterMarkStyle"0);
            FileWidth 
= Methods.Req.GetInt("Width",550);
            FileHeigth 
= Methods.Req.GetInt("Heigth"400);
            FileAuto 
= Methods.Req.GetString("Auto");

            
try
            
{
                HttpPostedFile postedFile 
= Request.Files["Filedata"];
                sFilePathName 
= postedFile.FileName;
                FileSize 
= postedFile.ContentLength;  //===========获取文件的大小

                
if (FileSize <= 0)
                
{
                    Response.Clear();
                    Response.Write(
"false|您没有选择文件!");
                    Response.End();
                }

                
else
                
{
                    sFileName 
= sFilePathName.Substring(sFilePathName.LastIndexOf("\\"+ 1);
                    FileExtName 
= sFilePathName.Substring(sFilePathName.LastIndexOf("."+ 1);
                    
if (IsValidFileType(FileExtName) == false)
                    
{
                        Response.Clear();
                        Response.Write(
"false|系统禁止上传此格式的文件!");
                        Response.End();
                    }

                    
else
                    
{
                        GotoUploadFile(postedFile);
                    }

                }

            }

            
catch { }
            
        }


        
protected void GotoUploadFile(HttpPostedFile postedFile)
        
{
            
string NewFileName = DateTime.Now.ToString("yyyyMMddhhmmss"+ FileSize + "." + FileExtName;
            
string NewFileName2 = DateTime.Now.ToString("yyyyMMddhhmmss"+ FileSize + "_1." + FileExtName;
            
string NewFilePath = "";
            
if (Model.Article.Setting.Upload_SortFile == true)
            
{
                
if (Model.Article.Setting.Upload_FolderStyle != "")
                
{
                    FileURL 
= Model.Article.Setting.Upload_Prefix + Model.Article.Setting.Upload_Folder + "/" + FileExtName + "/" + DateTime.Now.ToString(Model.Article.Setting.Upload_FolderStyle) + "/" + NewFileName;
                    FileURL2 
= Model.Article.Setting.Upload_Prefix + Model.Article.Setting.Upload_Folder + "/" + FileExtName + "/" + DateTime.Now.ToString(Model.Article.Setting.Upload_FolderStyle) + "/" + NewFileName2;
                    NewFilePath 
= AppPath + Model.Article.Setting.Upload_Folder.Replace("/""\\"+ "\\" + FileExtName + "\\" + DateTime.Now.ToString(Model.Article.Setting.Upload_FolderStyle).Replace("/""\\");
                }

                
else
                
{
                    FileURL 
= Model.Article.Setting.Upload_Prefix + Model.Article.Setting.Upload_Folder + "/" + FileExtName + "/" + NewFileName;
                    FileURL2 
= Model.Article.Setting.Upload_Prefix + Model.Article.Setting.Upload_Folder + "/" + FileExtName + "/" + NewFileName2;
                    NewFilePath 
= AppPath + Model.Article.Setting.Upload_Folder.Replace("/""\\"+ "\\" + FileExtName;
                }


            }

            
else
            
{
                
if (Model.Article.Setting.Upload_FolderStyle != "")
                
{
                    FileURL 
= Model.Article.Setting.Upload_Prefix + Model.Article.Setting.Upload_Folder + "/" + DateTime.Now.ToString(Model.Article.Setting.Upload_FolderStyle) + "/" + NewFileName;
                    FileURL2 
= Model.Article.Setting.Upload_Prefix + Model.Article.Setting.Upload_Folder + "/" + DateTime.Now.ToString(Model.Article.Setting.Upload_FolderStyle) + "/" + NewFileName2;
                    NewFilePath 
= AppPath + Model.Article.Setting.Upload_Folder.Replace("/""\\"+ "\\" + DateTime.Now.ToString(Model.Article.Setting.Upload_FolderStyle).Replace("/""\\");
                }

                
else
                
{
                    FileURL 
= Model.Article.Setting.Upload_Prefix + Model.Article.Setting.Upload_Folder + "/" + NewFileName;
                    FileURL2 
= Model.Article.Setting.Upload_Prefix + Model.Article.Setting.Upload_Folder + "/" + NewFileName2;
                    NewFilePath 
= AppPath + Model.Article.Setting.Upload_Folder.Replace("/""\\");
                }

            }


            TT.WebManager.Methods.IIOO.CreateDirectory(NewFilePath);

            FileAppPath 
= NewFilePath + "\\" + NewFileName;
            FileAppPath2 
= NewFilePath + "\\" + NewFileName2;

            postedFile.SaveAs(FileAppPath);
            
switch (FileExtName.ToLower())
            
{
                
case "jpg":
                
case "jpeg":
                
case "gif":
                
case "bmp":
                
case "png":
                    
//==========生成水印=============
                    switch (WaterMarkStyle)
                    
{
                        
case 1:
                            CreateWeaterText(FileAppPath, FileAppPath2, Model.Article.Setting.WaterMark_Text, FileExtName);
                            FileURL 
= FileURL2;
                            
break;
                        
case 2:
                            CreateWeaterPicture(FileAppPath, FileAppPath2, Server.MapPath(Model.Article.Setting.WaterMark_Picture), FileExtName);
                            FileURL 
= FileURL2;
                            
break;
                        
default:
                            
break;
                    }

                    
break;
            }


            
string ReturnString = sFileName + "|" + FileURL + "|" + FileWidth + "|" + FileHeigth + "|" + FileAuto;

            Response.Clear();
            Response.Write(
"true|"+ReturnString);
            Response.End();
        }


        
private void CreateWeaterText(string paraOldFileName, string paraNewsFileName, string AddText, string FileExtensionName)
        
{
            System.Drawing.Image image 
= System.Drawing.Image.FromFile(paraOldFileName);
            System.Drawing.Graphics g 
= System.Drawing.Graphics.FromImage(image);

            
//文字抗锯齿
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            g.SmoothingMode 
= System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.CompositingQuality 
= System.Drawing.Drawing2D.CompositingQuality.HighQuality;

            g.DrawImage(image, 
00, image.Width, image.Height);
            
//Font font = new Font("黑体", 14, FontStyle.Bold);
            
//Brush b = new SolidBrush(Color.Yellow);
            Font font = new Font(Model.Article.Setting.WaterMark_FontFamily, Model.Article.Setting.WaterMark_FontSize, FontStyle.Bold);
            Brush b 
= new SolidBrush(Methods.TypeParse.StrToColor(Model.Article.Setting.WaterMark_FontColor));






            
int Xpos = 0;
            
int Ypos = 0;
            SizeF crsize 
= new SizeF();
            crsize 
= g.MeasureString(AddText, font);
            
int crsize_With = Convert.ToInt32(crsize.Width);
            
int crsize_Height = Convert.ToInt32(crsize.Height);

            
int WaterMark_xPos = 10;
            
int WaterMark_yPos = 10;

            
switch (Model.Article.Setting.WaterMark_Position)//==========从图片的左上角开始算起(0,0)
            {
                
case 1:
                    Xpos 
= WaterMark_xPos;
                    Ypos 
= WaterMark_yPos;
                    
break;
                
case 2:
                    Xpos 
= image.Width - (crsize_With + WaterMark_xPos);
                    Ypos 
= WaterMark_yPos;
                    
break;
                
case 3:
                    Xpos 
= WaterMark_xPos;
                    Ypos 
= image.Height - (crsize_Height + WaterMark_yPos);
                    
break;
                
case 4:
                    Xpos 
= image.Width - (crsize_With + WaterMark_xPos);
                    Ypos 
= image.Height - (crsize_Height + WaterMark_yPos);
                    
break;
            }


            
//画阴影
            PointF pt = new PointF(00);
            System.Drawing.Brush TransparentBrush0 
= new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(50, System.Drawing.Color.Black));
            System.Drawing.Brush TransparentBrush1 
= new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(20, System.Drawing.Color.Black));

            g.DrawString(AddText, font, TransparentBrush0, Xpos, Ypos 
+ 1);
            g.DrawString(AddText, font, TransparentBrush0, Xpos 
+ 1, Ypos);
            g.DrawString(AddText, font, TransparentBrush1, Xpos 
+ 1, Ypos + 1);
            g.DrawString(AddText, font, TransparentBrush1, Xpos, Ypos 
+ 2);
            g.DrawString(AddText, font, TransparentBrush1, Xpos 
+ 2, Ypos);

            TransparentBrush0.Dispose();
            TransparentBrush1.Dispose();


            g.DrawString(AddText, font, b, Xpos, Ypos);

            
switch (FileExtensionName.ToLower())
            
{
                
case "jpg":
                
case "jpeg":
                    image.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    
break;
                
case "gif":
                    image.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
                    
break;
                
case "bmp":
                    image.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Bmp);
                    
break;
                
case "png":
                    image.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
                    
break;
            }

            g.Dispose();

            image.Save(paraNewsFileName);
            image.Dispose();
            Response.Clear();

            
if (File.Exists(paraOldFileName) == true)
            
{
                File.Delete(paraOldFileName);
            }

        }


        
private void CreateWeaterPicture(string paraOldFileName, string paraNewsFileName, string AddPicture, string FileExtensionName)
        
{
            System.Drawing.Image image 
= System.Drawing.Image.FromFile(paraOldFileName);
            System.Drawing.Image copyImage 
= System.Drawing.Image.FromFile(AddPicture);

            ImageAttributes imageAttributes 
= new ImageAttributes();
            ColorMap colorMap 
= new ColorMap();
            colorMap.OldColor 
= Color.FromArgb(20002000);
            colorMap.NewColor 
= Color.FromArgb(0000);
            ColorMap[] remapTable 
= { colorMap };
            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
            
float[][] colorMatrixElements = {
                                                
new float[] {1.0f,  0.0f,  0.0f,  0.0f0.0f},
                                                
new float[] {0.0f,  1.0f,  0.0f,  0.0f0.0f},
                                                
new float[] {0.0f,  0.0f,  1.0f,  0.0f0.0f},
                                                
new float[] {0.0f,  0.0f,  0.0f,  Model.Article.Setting.WaterMark_Transparency, 0.0f},
                                                
new float[] {0.0f,  0.0f,  0.0f,  0.0f1.0f}
                                            }
;
            ColorMatrix colorMatrix 
= new ColorMatrix(colorMatrixElements);
            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);


            Graphics g 
= Graphics.FromImage(image);


            
//PointF pt = new PointF(0, 0);
            
//System.Drawing.Brush TransparentBrush0 = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(50, System.Drawing.Color.));
            
//System.Drawing.Brush TransparentBrush1 = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(20, System.Drawing.Color.Black));

            
//g.DrawString(AddText, font, TransparentBrush0, pt.X, pt.Y + 1);

            
//g.DrawString(AddText, font, TransparentBrush0, pt.X + 1, pt.Y);

            
//g.DrawString(AddText, font, TransparentBrush1, pt.X + 1, pt.Y + 1);

            
//g.DrawString(AddText, font, TransparentBrush1, pt.X, pt.Y + 2);

            
//g.DrawString(AddText, font, TransparentBrush1, pt.X + 2, pt.Y);

            
//TransparentBrush0.Dispose();

            
//TransparentBrush1.Dispose();


            
//设定合成图像的质量
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            
//设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            
//设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            
int xPos = image.Width - copyImage.Width - 10;
            
int yPos = image.Height - copyImage.Height - 10;

            
switch (Model.Article.Setting.WaterMark_Position)//==========从图片的左上角开始算起(0,0)
            {
                
case 1:
                    xPos 
= 10;
                    yPos 
= 10;
                    
break;
                
case 2:
                    xPos 
= image.Width - copyImage.Width - 10;
                    yPos 
= 10;
                    
break;
                
case 3:
                    xPos 
= 10;
                    yPos 
= image.Height - copyImage.Height - 10;
                    
break;
                
case 4:
                    xPos 
= image.Width - copyImage.Width - 10;
                    yPos 
= image.Height - copyImage.Height - 10;
                    
break;
            }


            g.DrawImage(copyImage, 
new Rectangle(xPos, yPos, copyImage.Width, copyImage.Height), 00, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel, imageAttributes);

            
switch (FileExtensionName.ToLower())
            
{
                
case "jpg":
                
case "jpeg":
                    image.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    
break;
                
case "gif":
                    image.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
                    
break;
                
case "bmp":
                    image.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Bmp);
                    
break;
                
case "png":
                    image.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
                    
break;
            }

            g.Dispose();

            image.Save(paraNewsFileName);
            image.Dispose();
            imageAttributes.Dispose();

            Response.Clear();

            
if (File.Exists(paraOldFileName) == true)
            
{
                File.Delete(paraOldFileName);
            }


            
// return paraNewsFileName;
        }


        
protected bool IsValidFileType(string ExtName)
        
{
            
if (Model.Article.Setting.Upload_ContontFileStyle.Trim() == "")
                
return true;

            
string[] AcceptedFileTypes = Model.Article.Setting.Upload_ContontFileStyle.Split(new char[] '|' });
            
for (int i = 0; i < AcceptedFileTypes.Length; i++)
            
{
                
if (ExtName.ToLower() == AcceptedFileTypes[i].ToLower())
                
{
                    
return true;
                }

            }

            
return false;
        }

    }

}

三、相应的aspx页面代码


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
  
<title>FLASH 上传测试</title>
  
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
  
<link href="../images/style.css" rel="stylesheet" type="text/css" />
  
<script language="javascript">AC_FL_RunContent = 0;</script>
  
<script src="../javascript/AC_RunActiveContent.js" language="javascript"></script>
  
</head>
<body>

<!--影片中使用的 URL-->
<!--影片中使用的文本-->
<!-- saved from url=(0013)about:internet -->
<script language="javascript">
    
if (AC_FL_RunContent == 0{
        alert(
"此页需要 AC_RunActiveContent.js");
    }
 else {
        AC_FL_RunContent(
            
'codebase''http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
            
'width''400',
            
'height''56',
            
'src''../SWFUpload/SWFFileUpload',
            
'quality''high',
            
'pluginspage''http://www.macromedia.com/go/getflashplayer',
            
'align''middle',
            
'play''true',
            
'loop''true',
            
'scale''showall',
            
'wmode''window',
            
'devicefont''false',
            
'id''SWFFileUpload',
            
'bgcolor''#ffffff',
            
'name''SWFFileUpload',
            
'menu''true',
            
'allowFullScreen''false',
            
'allowScriptAccess','sameDomain',
            
'movie''../SWFUpload/SWFFileUpload',
            
'salign''',
            
'FlashVars','ComJsFun=UploadForEditor'
            ); 
//end AC code
    }

//src和movie属性为Flash文件地址,请勿写.swf后缀名
//
FlashVars为给Flash设置的参数。
</script>

<noscript>
    
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="400" height="56" id="SWFFileUpload" align="middle">
    
<param name="allowScriptAccess" value="sameDomain" />
    
<param name="allowFullScreen" value="false" />
    
<param name="movie" value="../SWFUpload/SWFFileUpload.swf" />
    
<param name="quality" value="high" />
    
<param name="bgcolor" value="#ffffff" />
    
<param name="FlashVars" value="ComJsFun=UploadForEditor"/>
    
<embed src="../SWFUpload/SWFFileUpload.swf" quality="high" bgcolor="#ffffff" width="400" height="56" name="SWFFileUpload" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
    
</object>
</noscript>

<div id="showInfo"></div>

 
<script language="javascript" type="text/javascript">
function UploadForEditor(Value){
   alert(Value);
   
//var RSArr = Value.split("|");
   //UploaFile(RSArr[0],RSArr[1],RSArr[2],RSArr[3],RSArr[4]);
}
 




</script>
</body>
</html>
posted on 2009-03-23 10:32  dadamoney  阅读(756)  评论(0编辑  收藏  举报