别人是说了再做,我是做了再说;别人说了不一定做,我是做了不一定说。

.Net 图片上传的一个类库的源码

                                   

上传图片到服务器上是网站开发中很常用的功能,它的实现也很简单,可以新建一个上传类UpLoadAndSaveImage,这个类中包含三个函数UpLoadAndSave,CreateFilePath,SaveToServer。使用时调用下面的UpLoadAndSave函数就可以了,该函数第一个参数为要上传的图片数据,第二个参数为上传的虚拟路径(相对路径),第三个参数为上传图片的格式,第四个参数为上传的物理路径。在这个函数中调用CreateFilePath函数产生随机的图片名称,最后再调用SaveToServer保存图片到服务器上。
public string UpLoadAndSave(byte[] data,refstring virPath,string fext,string physicPath)
{
// 返回文件物理地址,修改虚拟地址
if(data==null||virPath==null||fext==null||physicPath=="")
{
throw new Exception(" 非法参数" );
}
string rtnValue=SaveToServer(data,fext,physicPath,data.Length);
virPath += rtnValue;
physicPath+=rtnValue;
return physicPath;
}
private string CreateFilePath(string fext)
{
string filePath="";
Random rd=new Random();
filePath+=DateTime.Now.Year.ToString("0000");
filePath+=DateTime.Now.Month.ToString("00");
filePath+=DateTime.Now.Date.ToString("00");
filePath+=DateTime.Now.Hour.ToString("00");
filePath+=DateTime.Now.Minute.ToString("00");
filePath+=DateTime.Now.Second.ToString("00");
filePath+=DateTime.Now.Millisecond.ToString("00");
filePath+=rd.Next(99).ToString("00");
filePath+="."+fext;
return filePath;
}
private string SaveToServer(byte[] data,string fext,string physicPath,int fileLen)
{
string filePath=CreateFilePath(fext);
string rtnValue=filePath;
filePath=filePath.Insert(0,@physicPath);
if(File.Exists(filePath))
{
filePath=CreateFilePath(fext);
rtnValue=filePath;
}
FileStream fs=new FileStream(filePath,FileMode.CreateNew);
fs.Write(data,0,fileLen);
fs.Close();
return rtnValue;
}

//在其他页面调用该上传类,见下面的实例:
UpLoadAndSaveImage upload=new UpLoadAndSaveImage();
try
{
string virPath="UploadFiles/";
string physicPath=Server.MapPath(Request.ApplicationPath+"/"+"UploadFiles/");
string fext=this.File1.PostedFile.FileName;
if(fext.Length==0)
{
return;
}

fext=Path.GetExtension(fext).ToLower();
if(fext!=".jpg"&&fext!=".gif"&&fext!=".bmp"&&fext!=".doc"&&fext!=".rar"&&fext!=".zip"&&fext!=".jpeg")
{
Response.Write("<script>alert('Invalid file format,the file format must be jpg or jpeg or gif
or bmp or doc or rar or zip')</script>");
return;
}

byte[] data=newbyte[this.File1.PostedFile.ContentLength];

this.File1.PostedFile.InputStream.Read(data,0,this.File1.PostedFile.ContentLength);

physicPath=upload.UpLoadAndSave(data,ref virPath,fext,physicPath);

url=virPath;

if(Session["PhotoUrl"]==null)
{
ArrayList al=new ArrayList();
al.Add(physicPath);
Session["PhotoUrl"]=al;
}
else
{
ArrayList al2=(ArrayList)Session["PhotoUrl"];

al2.Add(physicPath);

Session["PhotoUrl"]=al2;
}
}
catch(Exception ex)
{
Response.Write("<script>alert('"+ex.Message+"');</script>");
}

// 如果要指定上传图片的大小,可以在调用该上传类前生成,见下面的实例:

try
{
empPic = new Bitmap(File1.PostedFile.InputStream);
}
catch
{
Script.Alert(" 图片格式错误!" );
return false;
}
Bitmap picSmall = new Bitmap(empPic,227,91); // 生成图片大小
MemoryStream stream = new MemoryStream();

picSmall.Save(stream,ImageFormat.Jpeg);
byte[] byteArray = stream.ToArray();
PathName1="Photo/";
PathName=Server.MapPath(Request.ApplicationPath+"/Photo/");
UpLoadAndSaveImage upimage=new UpLoadAndSaveImage();
PathName=upimage.UpLoadAndSave(byteArray,ref PathName1,".jpg",PathName);

以下是我曾经写的图片上传类,带水印功能:

//生成缩略图功能。
using System;
using System.IO;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Drawing;
namespace MyUplod
{
    /// <summary>
    /// 非寒上传类(图片)。 作者:非寒.功能:上传文件操作(主要用于图片上传);
    /// </summary>
    public class Upload
    {
        private int _Error = 0;//返回上传状态。
        private int _MaxSize = 5120000;//最大单个上传文件 (默认)
        private string _FileType = "jpg/gif/bmp/png";//所支持的上传类型用"/"隔开
        private string _SavePath = System.Web.HttpContext.Current.Server.MapPath(".") + "\\";//保存文件的实际路径
        private int _SaveType = 0;//上传文件的类型,0代表自动生成文件名
        private HtmlInputFile _FormFile;//上传控件。
        private string _InFileName = "";//非自动生成文件名设置。
        private string _OutFileName = "";//输出文件名。
        private bool _IsCreateImg = true;//是否生成缩略图。
        private bool _Iss = false;//是否有缩略图生成.
        private int _Height = 0;//获取上传图片的高度
        private int _Width = 0;//获取上传图片的宽度
        private int _sHeight = 120;//设置生成缩略图的高度
        private int _sWidth = 120;//设置生成缩略图的宽度
        private bool _IsDraw = false;//设置是否加水印
        private int _DrawStyle = 0;//设置加水印的方式0:文字水印模式,1:图片水印模式,2:不加
        private int _DrawString_x = 10;//绘制文本的X坐标(左上角)
        private int _DrawString_y = 10;//绘制文本的Y坐标(左上角)
        private string _AddText = "杭州五维多媒体\nHTTP://WWW.5D.CN";//设置水印内容
        private string _Font = "宋体";//设置水印字体
        private int _FontSize = 12;//设置水印字大小
        private int _FileSize = 0;//获取已经上传文件的大小
        private string _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(".") + "/images/5dm_new.jpg";//图片水印模式下的覆盖图片的实际地址
       
        /// <summary>
        /// Error返回值,1、没有上传的文件。2、类型不允许。3、大小超限。4、未知错误。0、上传成功。
        /// </summary>
        public int Error
        {
            get { return _Error; }
        }
        /// <summary>
        /// 最大单个上传文件
        /// </summary>
        public int MaxSize
        {
            set { _MaxSize = value; }
        }
        /// <summary>
        /// 所支持的上传类型用"/"隔开
        /// </summary>
        public string FileType
        {
            set { _FileType = value; }
        }
        /// <summary>
        /// //保存文件的实际路径
        /// </summary>
        public string SavePath
        {
            set { _SavePath = System.Web.HttpContext.Current.Server.MapPath(value); }
            get {return _SavePath;}
        }
        /// <summary>
        /// 上传文件的类型,0代表自动生成文件名
        /// </summary>
        public int SaveType
        {
            set { _SaveType = value; }
        }
        /// <summary>
        /// 上传控件
        /// </summary>
        public HtmlInputFile FormFile
        {
            set { _FormFile = value; }
        }
        /// <summary>
        /// //非自动生成文件名设置。
        /// </summary>
        public string InFileName
        {
            set { _InFileName = value; }
        }
        /// <summary>
        /// 输出文件名
        /// </summary>
        public string OutFileName
        {
            get { return _OutFileName; }
            set { _OutFileName = value; }
        }
        /// <summary>
        /// 是否有缩略图生成.
        /// </summary>
        public bool Iss
        {
            get { return _Iss; }
        }
        /// <summary>
        /// //获取上传图片的宽度
        /// </summary>
        public int Width
        {
            get { return _Width; }
        }
        /// <summary>
        /// //获取上传图片的高度
        /// </summary>
        public int Height
        {
            get { return _Height; }
        }
        /// <summary>
        /// 设置缩略图的宽度
        /// </summary>
        public int sWidth
        {
            get { return _sWidth; }
            set { _sWidth = value; }
        }
        /// <summary>
        /// 设置缩略图的高度
        /// </summary>
        public int sHeight
        {
            get { return _sHeight; }
            set { _sHeight = value; }
        }
        /// <summary>
        /// 是否生成缩略图
        /// </summary>
        public bool IsCreateImg
        {
            get { return _IsCreateImg; }
            set { _IsCreateImg = value; }
        }
        /// <summary>
        /// 是否加水印
        /// </summary>
        public bool IsDraw
        {
            get { return _IsDraw; }
            set { _IsDraw = value; }
        }
        /// <summary>
        /// 设置加水印的方式0:文字水印模式,1:图片水印模式,2:不加
        /// </summary>
        public int DrawStyle
        {
            get { return _DrawStyle; }
            set { _DrawStyle = value; }
        }
        /// <summary>
        /// 绘制文本的X坐标(左上角)
        /// </summary>
        public int DrawString_x
        {
            get { return _DrawString_x; }
            set { _DrawString_x = value; }
        }
        /// <summary>
        /// 绘制文本的Y坐标(左上角)
        /// </summary>
        public int DrawString_y
        {
            get { return _DrawString_y; }
            set { _DrawString_y = value; }
        }
        /// <summary>
        /// 设置文字水印内容
        /// </summary>
        public string AddText
        {
            get { return _AddText; }
            set { _AddText = value; }
        }
        /// <summary>
        /// 设置文字水印字体
        /// </summary>
        public string Font
        {
            get { return _Font; }
            set { _Font = value; }
        }
        /// <summary>
        /// 设置文字水印字的大小
        /// </summary>
        public int FontSize
        {
            get { return _FontSize; }
            set { _FontSize = value; }
        }
        public int FileSize
        {
            get { return _FileSize; }
            set { _FileSize = value; }
        }
        /// <summary>
        /// 图片水印模式下的覆盖图片的实际地址
        /// </summary>
        public string CopyIamgePath
        {
            set { _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(value); }
        }
       
        //获取文件的后缀名
        private string GetExt(string path)
        {
            return Path.GetExtension(path);
        }
        //获取输出文件的文件名。
        private string FileName(string Ext)
        {
            if (_SaveType == 0 || _InFileName.Trim() == "")
                return DateTime.Now.ToString("yyyyMMddHHmmssfff") + Ext;
            else
                return _InFileName;
        }
        //检查上传的文件的类型,是否允许上传。
        private bool IsUpload(string Ext)
        {
            Ext = Ext.Replace(".", "");
            bool b = false;
            string[] arrFileType = _FileType.Split(';');
            foreach (string str in arrFileType)
            {
                if (str.ToLower() == Ext.ToLower())
                {
                    b = true;
                    break;
                }
            }
            return b;
        }
        //上传主要部分。
        public void Open()
        {
            HttpPostedFile hpFile = _FormFile.PostedFile;
            if (hpFile == null || hpFile.FileName.Trim() == "")
            {
                _Error = 1;
                return;
            }

            string Ext = GetExt(hpFile.FileName);
            if (!IsUpload(Ext))
            {
                _Error = 2;
                return;
            }

            int iLen = hpFile.ContentLength;
            if (iLen > _MaxSize)
            {
                _Error = 3;
                return;
            }

            try
            {
              
                    if (!Directory.Exists(_SavePath))
                        Directory.CreateDirectory(_SavePath);
                    byte[] bData = new byte[iLen];
                    hpFile.InputStream.Read(bData, 0, iLen);
                    string FName;
                    FName = FileName(Ext);
                    string TempFile = "";
                    if (_IsDraw)
                    {
                        TempFile=FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString();
                    }
                    else
                    {
                        TempFile = FName;
                    }
                    FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create);
                    newFile.Write(bData, 0, bData.Length);
                    newFile.Flush();
                    int _FileSizeTemp = hpFile.ContentLength;
                   
                    if (_IsDraw)
                    {
                        if (_DrawStyle == 0)
                        {
                            System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile);
                            Graphics g = Graphics.FromImage(Img1);
                            g.DrawImage(Img1, 100, 100, Img1.Width, Img1.Height);
                            Font f = new Font(_Font, _FontSize);
                            Brush b = new SolidBrush(Color.Red);
                            string addtext = _AddText;
                            g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y);
                            g.Dispose();
                            Img1.Save(_SavePath + FName);
                            Img1.Dispose();


                        }
                        else
                        {
                            System.Drawing.Image image = System.Drawing.Image.FromStream(newFile);
                            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath);
                            Graphics g = Graphics.FromImage(image);
                            g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 5, image.Height - copyImage.Height - 5, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                            g.Dispose();
                            image.Save(_SavePath + FName);
                            image.Dispose();
                        }
                    }

                try
                {
                    //获取图片的高度和宽度
                    System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile);
                    _Width = Img.Width;
                    _Height = Img.Height;
                    //生成缩略图部分
                    if (_IsCreateImg)
                    {
                        //如果上传文件小于15k,则不生成缩略图。
                        if (iLen > 15360)
                        {

                            System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
                            newImg.Save(_SavePath + FName.Split('.').GetValue(0).ToString() + "_s." + FName.Split('.').GetValue(1).ToString());
                            newImg.Dispose();
                            _Iss = true;
                        }
                    }
                    if (_IsDraw)
                    {
                        if (File.Exists(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString()))
                        {
                            newFile.Dispose();
                            File.Delete(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString());
                        }
                    }
                }
                catch { }
                newFile.Close();
                newFile.Dispose();
                _OutFileName = FName;
                _FileSize = _FileSizeTemp;
                _Error = 0;
                return;
            }
            catch
            {
                _Error = 4;
                return;
            }
        }
    }
}

posted @ 2007-02-06 20:51  碧血黄沙-java、c#  阅读(2292)  评论(0编辑  收藏  举报