通用上传文件类 (转)

/************************************************************************************
 *      Copyright (C) 2007 supesoft.com,All Rights Reserved          *
 *      File:                  *
 *    FileUpLoadCommon.cs                                           *
 *      Description:                *
 *     通用上传文件类                    *
 *      Author:                  *
 *    Lzppcc                      *
 *    Lzppcc@hotmail.com             *
 *    http://www.supesoft.com            *
 *      Finish DateTime:               *
 *    2007年8月6日              *
 *      History:                 *
 ***********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.IO;
using System.Web;
using System.Drawing;

namespace FrameWork
{
    /// <summary>
    /// 通用上传文件类
    /// </summary>
    public class FileUpLoadCommon
    {
        #region "Private Variables"
        private string _path;                   // 上传文件的路径
        private string _fileName;               // 文件名称
        private string _newFileName  ="";            // 新的文件名
        private string _fileName_s;             // 缩略图文件名称
        private string _fileName_sy;            // 水印图文件名称(文字)
        private string _fileName_syp;           // 水印图文件名称(图片)
        private string _webFilePath;            // 服务器端文件路径
        private string _webFilePath_s;        // 服务器端缩略图路径
        private string _webFilePath_sy;        // 服务器端带水印图路径(文字)
        private string _webFilePath_syp;       // 服务器端带水印图路径(图片)
        private string _webFilePath_sypf;      // 服务器端水印图路径(图片)

        private string _errorMsg;               // 错误信息
        private bool _isDate = true;            // 是否加上日期
        private bool _isThumbnail = true;       // 是否产生缩图
        private bool _isWatermarkT = false;      // 是否产生水印文字
        private bool _isWatermarkP = false;      // 是否产生水印叠加图片
        private bool _isOnly = true;            // 是否只产生一个文件,原始文件+加水印文字+加水印图片


        //private bool _isImage = true;           // 是否只充许图片

        private int _width = Common.UpImgWidth;               // 缩图宽度
        private int _height = Common.UpImgHeight;               // 缩图高度
        private string _mode = "Auto";        // 缩图模式 "HW"://指定高宽缩放(可能变形)  "W"//指定宽,高按比例 "H"//指定高,宽按比例  "Cut"://指定高宽裁减(不变形) Auto:自动
        private string _addText = "Moliyo.com";   // 水印文字
        private string _addPicture = Common.UpLoadDir+"shuiyin.jpg";   // 水印文字

        private int _fileSize = 0;          // 图片大小
        private int _fileWidth = 0;         // 图片宽度
        private int _fileHeight = 0;        // 图片高度
        private string _fileType;           // 文件类型
        #endregion

        #region 属性 -- 旧文件名
        /// <summary>
        /// 旧文件名
        /// </summary>
        public string fileName
        {
            get
            {
                return _fileName;
            }
        }
        #endregion

        #region 属性 -- 上传后新文件名
        /// <summary>
        /// 上传后新文件名
        /// </summary>
        public string newFileName
        {
            get
            {
                return _newFileName;
            }
        }
        #endregion

        #region 属性 -- 缩图文件名
        /// <summary>
        /// 缩图文件名
        /// </summary>
        public string fileName_s
        {
            get
            {
                return _fileName_s;
            }
        }
        #endregion

        #region 属性 -- 加文字水印的图片
        /// <summary>
        /// 加文字水印的图片
        /// </summary>
        public string fileName_sy
        {
            get
            {
                return _fileName_sy;
            }
        }
        #endregion

        #region 属性 -- 加图片水印的图片
        /// <summary>
        /// 加图片水印的图片
        /// </summary>
        public string fileName_syp
        {
            get
            {
                return _fileName_syp;
            }
        }
        #endregion

        #region 属性 -- 上传的文件的路径
        /// <summary>
        /// 上传的文件的路径
        /// </summary>
        public string path
        {
            get
            {
                return _path;
            }
        }
        #endregion

        #region 属性 -- 文件大小
        /// <summary>
        /// 文件大小
        /// </summary>
        public int fileSize
        {
            get
            {
                return _fileSize;
            }
        }
        #endregion

        #region 属性 -- 图片原始的宽度
        /// <summary>
        /// 图片原始的宽度
        /// </summary>
        public int fileWidth
        {
            get
            {
                return _fileWidth;
            }
        }
        #endregion

        #region 属性 -- 图片原始的高度
        /// <summary>
        /// 图片原始的高度
        /// </summary>
        public int fileHeight
        {
            get { return _fileHeight; }
        }
        #endregion

        #region 属性 -- 文件的类型
        /// <summary>
        /// 文件的类型
        /// </summary>
        public string fileType
        {
            get { return _fileType; }
        }
        #endregion

        #region 属性 -- 设置水印文字
        /// <summary>
        /// 设置水印文字
        /// </summary>
        public string addText
        {
            set { _addText = value; }
        }
        #endregion

        #region 属性 -- 设置水印图片
        /// <summary>
        /// 设置水印图片
        /// </summary>
        public string addPicture
        {
            set { _addPicture = value; }
        }
        #endregion
       
        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public FileUpLoadCommon()
            : this("/public/", true)
        {

        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="isDate">是否按日期创建目录</param>
        public FileUpLoadCommon(string filePath, bool isDate)
        {
            _path = filePath;
            _isDate = isDate;
            if (_isDate)
                _path += DateTime.Now.ToString("yyyyMMdd") + "/";

            string p = HttpContext.Current.Server.MapPath(_path);
            //如果目录不存在,将创建目录
            if (!Directory.Exists(p))
                Directory.CreateDirectory(p);
        }
        #endregion

        #region 方法 -- 保存文件

        /// <summary>
        /// 指定缩图的宽高
        /// </summary>
        /// <param name="fu">文件类型</param>
        /// <param name="Width">宽</param>
        /// <param name="Height">高</param>
        /// <returns></returns>
        public bool SaveImage(FileUpload fu, int Width, int Height)
        {
            _width = Width;
            _height = Height;
            return SaveImage(fu);
        }

        /// <summary>
        /// 指定缩图的宽高
        /// </summary>
        /// <param name="fu">文件类型</param>
        /// <param name="Width">宽</param>
        /// <param name="Height">高</param>
        /// <param name="Mode">缩图模式 "HW"://指定高宽缩放(可能变形)  "W"//指定宽,高按比例 "H"//指定高,宽按比例  "Cut"://指定高宽裁减(不变形) </param>
        /// <returns></returns>
        public bool SaveImage(FileUpload fu, int Width, int Height, string Mode)
        {
            _width = Width;
            _height = Height;
            _mode = Mode;
            return SaveImage(fu);
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="fu"></param>
        public void SaveFile(FileUpload fu)
        {
            if (fu.HasFile)
            {
                string name = fu.PostedFile.FileName;                           // 客户端文件路径
                FileInfo file = new FileInfo(name);
                _newFileName = CreateFileName() + file.Extension;                           // 新文件名
                _webFilePath = HttpContext.Current.Server.MapPath(_path + _newFileName);         // 服务器端文件路径
                //检查文件是否存在
                if (!File.Exists(_webFilePath))
                {
                    try
                    {
                        fu.SaveAs(_webFilePath);                                 // 使用 SaveAs 方法保存文件
                        _errorMsg = string.Format("提示:文件“{0}”成功上传,并生成“{1}”缩略图,文件类型为:{2},文件大小为:{3}B", _newFileName, _fileName_s, fu.PostedFile.ContentType, fu.PostedFile.ContentLength);
                    }
                    catch (Exception ex)
                    {
                        _errorMsg = "提示:文件上传失败,失败原因:" + ex.Message;
                    }
                }
                else
                    _errorMsg = "提示:文件已经存在,请重命名后上传";
            }
        }
        #endregion

        #region 方法 -- 保存图片
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="fu"></param>
        public bool SaveImage(FileUpload fu)
        {
            if (fu.HasFile)
            {
                string fileContentType = fu.PostedFile.ContentType;
                if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
                {
                    string name = fu.PostedFile.FileName;                           // 客户端文件路径
                    FileInfo file = new FileInfo(name);

                    _fileName = file.Name;                                // 文件名称
                    _newFileName = CreateFileName() + file.Extension;                           // 新文件名


                    _fileName_s = "s_" + _newFileName;                      // 缩略图文件名称
                    if (_isOnly)
                    {
                        _fileName_sy = _newFileName;                     // 水印图文件名称(文字)
                        _fileName_syp = _newFileName;                    // 水印图文件名称(图片)
                    }
                    else
                    {
                        _fileName_sy = "sy_" + _newFileName;                     // 水印图文件名称(文字)
                        _fileName_syp = "syp_" + _newFileName;                    // 水印图文件名称(图片)
                    }

                    _webFilePath = HttpContext.Current.Server.MapPath(_path + _newFileName);         // 服务器端文件路径
                    _webFilePath_s = HttpContext.Current.Server.MapPath(_path + _fileName_s);     // 服务器端缩略图路径
                    _webFilePath_sy = HttpContext.Current.Server.MapPath(_path + _fileName_sy);     // 服务器端带水印图路径(文字)
                    _webFilePath_syp = HttpContext.Current.Server.MapPath(_path + _fileName_syp);    // 服务器端带水印图路径(图片)
                    _webFilePath_sypf = HttpContext.Current.Server.MapPath(_addPicture);   // 服务器端水印图路径(图片)   

                    _fileType = fu.PostedFile.ContentType;
                    _fileSize = fu.PostedFile.ContentLength;

                    //检查文件是否存在
                    if (!File.Exists(_webFilePath))
                    {
                        try
                        {
                            fu.SaveAs(_webFilePath);                                 // 使用 SaveAs 方法保存文件    

                            if (_isWatermarkT)
                                AddShuiYinWord(_webFilePath, _webFilePath_sy);
                            if (_isWatermarkP)
                                AddShuiYinPic(_webFilePath, _webFilePath_syp, _webFilePath_sypf);
                            if (_isThumbnail)
                                MakeThumbnail(_webFilePath, _webFilePath_s, _width, _height, _mode);   // 生成缩略图方法

                            // 只有上传完了,才能获取图片大小
                            if (File.Exists(_webFilePath))
                            {
                                System.Drawing.Image originalImage = System.Drawing.Image.FromFile(_webFilePath);
                                try
                                {
                                    _fileHeight = originalImage.Height;
                                    _fileWidth = originalImage.Width;
                                }
                                finally
                                {
                                    originalImage.Dispose();
                                }
                            }

                            _errorMsg = string.Format("提示:文件“{0}”成功上传,并生成“{1}”缩略图,文件类型为:{2},文件大小为:{3}B", _newFileName, _fileName_s, fu.PostedFile.ContentType, fu.PostedFile.ContentLength);
                            return true;
                        }
                        catch (Exception ex)
                        {
                            _errorMsg = "提示:文件上传失败,失败原因:" + ex.Message;
                        }
                    }
                    else
                    {
                        _errorMsg = "提示:文件已经存在,请重命名后上传";
                    }
                }
                else
                {
                    _errorMsg = "提示:文件类型不符";
                }
            }
            return false;
        }
        #endregion

        #region 方法 -- 创建新的文件名
        /// <summary>
        /// 创建新的文件名
        /// </summary>
        /// <returns></returns>
        public string CreateFileName()
        {
            string guid = System.Guid.NewGuid().ToString().ToLower();
            guid = guid.Replace("-", "");

            return DateTime.Now.ToString("yyyyMMddhhmmss") + guid.Substring(0, 4);
        }
        #endregion

        #region 方法 -- 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename"></param>
        public static void DeleteFile(string filename)
        {
            string s = HttpContext.Current.Server.MapPath(filename);
            if (File.Exists(s))
            {
                try
                {
                    File.Delete(s);
                }
                catch
                { }
            }
        }
        #endregion

        #region 方法 -- 生成缩略图
        /**/
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>  
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            if (ow < towidth && oh < toheight)
            {
                originalImage.Save(thumbnailPath);
            }
            else
            {

                switch (mode.ToUpper())
                {
                    case "HW"://指定高宽缩放(可能变形)          
                        break;
                    case "W"://指定宽,高按比例            
                        toheight = originalImage.Height * width / originalImage.Width;
                        break;
                    case "H"://指定高,宽按比例
                        towidth = originalImage.Width * height / originalImage.Height;
                        break;
                    case "CUT"://指定高宽裁减(不变形)          
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                            ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    case "AUTO": //自动适应高度
                        if (ow > oh)
                        {
                            //newwidth = 200;
                            toheight = (int)((double)oh / (double)ow * (double)towidth);
                        }
                        else
                        {
                            //newheight = 200;
                            towidth = (int)((double)ow / (double)oh * (double)toheight);
                        }
                        break;
                    default:
                        break;
                }

                //新建一个bmp图片
                System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

                //新建一个画板
                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充
                g.Clear(System.Drawing.Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                    new System.Drawing.Rectangle(x, y, ow, oh),
                    System.Drawing.GraphicsUnit.Pixel);

                try
                {
                    //以jpg格式保存缩略图
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);

                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {

                    bitmap.Dispose();
                    g.Dispose();
                }
            }
            originalImage.Dispose();
        }
        #endregion

       
        #region 方法 -- 在图片上增加文字水印
        /**/
        /// <summary>
        /// 在图片上增加文字水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_sy">生成的带文字水印的图片路径</param>
        protected void AddShuiYinWord(string Path, string Path_sy)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            System.Drawing.Font f = new System.Drawing.Font("Verdana", 16);
            System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Blue);

            g.DrawString(_addText, f, b, 15, 15);
            g.Dispose();

            image.Save(Path_sy);
            image.Dispose();
        }
        #endregion

        #region 方法 -- 在图片上生成图片水印
        /**/
        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_syp">生成的带图片水印的图片路径</param>
        /// <param name="Path_sypf">水印图片路径</param>
        protected void AddShuiYinPic(string Path, string Path_syp, string Path_sypf)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_sypf);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();

            image.Save(Path_syp);
            image.Dispose();
        }
        #endregion
    }
}

转载于:https://www.cnblogs.com/yuewh491/archive/2007/08/09/848981.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值