我的番茄炒蛋
生活如此精彩,挑战无处不在!

导航

 

代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Moosoft.OA.Public
{
    
/// <summary>
    
/// 文件上传类
    
/// </summary>
    
/// <remarks>文件上传类</remarks>
    public class UploadFileClass
    {
        
private int _FileSize;
        
private string _FileType;
        
private string _UploadPath;
        
private string[] _FileExtent;
        
private IList<FileExtension> _FileHearCode = null;
        
/// <summary>
        
/// 生成缩略图模式
        
/// </summary>
        
/// <remarks>生成缩略图模式</remarks>
        public enum ThumbnailMode
        {
            
/// <summary>
            
/// 等高缩放
            
/// </summary>
            Height,
            
/// <summary>
            
/// 等宽缩放
            
/// </summary>
            Width,
            
/// <summary>
            
/// 高宽缩放(有可能变形)
            
/// </summary>
            HeightAndWidth,
            
/// <summary>
            
/// 剪切默认高宽
            
/// </summary>
            Cut
        }

        
/// <summary>
        
/// 构建一个文件上传对象
        
/// </summary>
        public UploadFileClass()
        {
            _FileSize 
= 1024 * 1024;
            _FileType 
= "jpg|gif|bmp|png|swf|rar|mp3|wma|doc|txt|exe|flv|docx|wmv|msi";
            _UploadPath 
= "/Uploads/";
            _FileExtent 
= _FileType.ToArray("|");
            
this.SLTHeight = 112;
            
this.SLTWidth = 150;
            
this.SLTLeave = 100;
            
this.WaterText = "";
            
this.WaterFile = "";

            _FileHearCode 
= new List<FileExtension>();
            _FileHearCode.Add(
new FileExtension("docx""8075"));
            _FileHearCode.Add(
new FileExtension("xlsx""8075"));
            _FileHearCode.Add(
new FileExtension("doc""208207"));
            _FileHearCode.Add(
new FileExtension("xls""208207"));
            _FileHearCode.Add(
new FileExtension("msi""208207"));
            _FileHearCode.Add(
new FileExtension("swf""6787"));
            _FileHearCode.Add(
new FileExtension("txt""6782"));
            _FileHearCode.Add(
new FileExtension("jpg""255216"));
            _FileHearCode.Add(
new FileExtension("gif""7173"));
            _FileHearCode.Add(
new FileExtension("bmp""6677"));
            _FileHearCode.Add(
new FileExtension("png""13780"));
            _FileHearCode.Add(
new FileExtension("rar""8297"));
            _FileHearCode.Add(
new FileExtension("flv""7076"));
            _FileHearCode.Add(
new FileExtension("mp3""255251"));
            _FileHearCode.Add(
new FileExtension("wma""4838"));
            _FileHearCode.Add(
new FileExtension("wmv""4838"));
            _FileHearCode.Add(
new FileExtension("exe""7790"));
        }

        
/// <summary>
        
/// 上传文件的大小,默认大小为1MB
        
/// </summary>
        public int FileSize
        {
            
get
            {
                
return _FileSize;
            }
            
set
            {
                _FileSize 
= value * 1024;
            }
        }

        
/// <summary>
        
/// 文件类型,默认值jpg|gif|png|bmp|swf|rar|mp3|wma|doc|txt|exe|flv|docx|wmv|msi
        
/// </summary>
        
/// <value>返回文件类型的字符串</value>
        public string FileType
        {
            
get
            {
                
return _FileType;
            }
            
set
            {
                _FileType 
= value;
                _FileExtent 
= value.ToArray("|");
            }
        }

        
/// <summary>
        
/// 上传的文件夹,默认路径"/Uploads/"
        
/// </summary>
        public string UploadPath
        {
            
get
            {
                
return _UploadPath;
            }
            
set
            {
                _UploadPath 
= value;
            }
        }

        
/// <summary>
        
/// 支持的文件类型数组
        
/// </summary>
        private string[] FileExtent
        {
            
get
            {
                
return _FileExtent;
            }
        }

        
/// <summary>
        
/// 缩略图宽度,默认宽度150px
        
/// </summary>
        public int SLTWidth
        {
            
get;
            
set;
        }

        
/// <summary>
        
/// 缩略图高度,默认高度112px
        
/// </summary>
        public int SLTHeight
        {
            
get;
            
set;
        }

        
/// <summary>
        
/// 缩略图清晰度(范围1-100),默认清晰度100
        
/// </summary>
        public int SLTLeave
        {
            
get;
            
set;
        }

        
/// <summary>
        
/// 水印文字,默认无水印文字
        
/// </summary>
        public string WaterText
        {
            
get;
            
set;
        }

        
/// <summary>
        
/// 水印图片,默认无水印文字,当该属性长度大于0的时候WaterText属性失效!
        
/// </summary>
        public string WaterFile
        {
            
get;
            
set;
        }

        
#region 文件头检查
        
private bool IsAllowedExtension(string FileUrl)
        {
            FileType obj_FileType 
= new FileType(HttpContext.Current.Server.MapPath(FileUrl));
            
string fileclass = obj_FileType.HeadCode;

            
bool Result = false;
            
if (obj_FileType.Extension.Remove(01).InArray(_FileExtent))
            {
                
for (int i = 0; i < _FileHearCode.Count; i++)
                {
                    FileInfo obj_File 
= new FileInfo(HttpContext.Current.Server.MapPath(FileUrl));
                    
if (obj_File.Extension.ToLower() == ("." + _FileHearCode[i].Extension))
                    {
                        
if (fileclass == _FileHearCode[i].HeadCode)
                        {
                            Result 
= true;
                            
break;
                        }
                    }
                }
            }
            
            
return Result;
        }
        
#endregion

        
#region 文件上传
        
/// <summary>
        
/// 上传文件
        
/// </summary>
        
/// <remarks>上传文件</remarks>
        
/// <param name="upFileControl">上传控件名称</param>
        
/// <param name="ReName">是否重命名</param>
        
/// <param name="CreatDirectory">是否创建一个和当前时间对应的文件夹</param>
        
/// <param name="page">页面Page对象</param>
        
/// <returns>返回上传的文件名</returns>
        public string FileSave(FileUpload upFileControl, bool ReName, bool CreatDirectory, Page page)
        {
            
string Result = "";

            
if (upFileControl.HasFile)
            {
                
string SaveUrl = this.UploadPath;
                
string FileName = upFileControl.FileName;
                
string tFileType = FileName.Substring(FileName.LastIndexOf("."+ 1).ToLower();
                
string[] tmp = this.FileType.ToArray("|");
                
if (ReName)
                {
                    FileName 
= DateTime.Now.ToString("yyyyMMddHHmmss"+ StringHelper.GetRamdonLower(6+ "." + tFileType;
                }
                
if (CreatDirectory)
                {
                    SaveUrl 
= SaveUrl + DateTime.Now.ToString("yyyy-MM-dd"+ "/";
                }
                DirectoryInfo dir 
= new DirectoryInfo(HttpContext.Current.Server.MapPath(SaveUrl));
                
if (!dir.Exists)
                {
                    dir.Create();
                }
                
bool flag = tFileType.InArray(this.FileExtent);
                
if (upFileControl.PostedFile.ContentLength <= this.FileSize)
                {
                    
if (flag)
                    {
                        upFileControl.SaveAs(HttpContext.Current.Server.MapPath(SaveUrl 
+ FileName));
                        Result 
= SaveUrl + FileName;
                        
if (!IsAllowedExtension(Result))
                        {
                            File.Delete(HttpContext.Current.Server.MapPath(Result));
                            UploadMsg(
"错误:文件格式和文件编码不匹配,请重新上传!", page);
                            Result 
= "";
                        }
                    }
                    
else
                    {
                        UploadMsg(
"错误:文件格式不合法! 请上传以下格式的文件: " + _FileType + "!", page);
                        
return "";
                    }
                }
                
else
                {
                    UploadMsg(
"错误:文件太大!上传文件的大小请不要超过" + FileSize + "K!", page);
                    
return "";
                }
            }
            
else
            {
                UploadMsg(
"错误:请选择要上传的文件" + FileSize + "K!", page);
                
return "";
            }

            
return Result;
        }

        
/// <summary>
        
/// 上传文件
        
/// </summary>
        
/// <remarks>上传文件</remarks>
        
/// <param name="upFileControl">上传控件名称</param>
        
/// <param name="ReName">是否随机重命名文件</param>
        
/// <param name="CreatDirectory">是否创建一个和当前时间对应的文件夹</param>
        
/// <param name="CreateSLT">是否创建缩略图</param>
        
/// <param name="page">页面Page对象</param>
        
/// <returns>返回上传的文件名</returns>
        public string FileSave(FileUpload upFileControl, bool ReName, bool CreatDirectory, bool CreateSLT, Page page)
        {
            
string tmp = FileSave(upFileControl, ReName, CreatDirectory,page);
            
if (tmp != "" && tmp != null)
            {
                FileInfo obj_File 
= new FileInfo(HttpContext.Current.Server.MapPath(tmp));
                
if (obj_File.Extension != ".jpg" && obj_File.Extension != ".gif" && obj_File.Extension != ".png" && obj_File.Extension != ".bmp")
                {
                    
if (CreateSLT)
                    {
                        
string[] url = tmp.ToArray("/");
                        
string SLTUrl = "";
                        
for (int i = 0; i < url.Length - 1; i++)
                        {
                            SLTUrl 
= SLTUrl + "/" + url.GetValue(i).ToString();
                        }
                        SLTUrl 
= SLTUrl + "/SLTImages/";
                        
if (!Directory.Exists(HttpContext.Current.Server.MapPath(SLTUrl)))
                        {
                            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(SLTUrl));
                        }
                        MakeThumbnail(HttpContext.Current.Server.MapPath(tmp), HttpContext.Current.Server.MapPath(SLTUrl 
+ url.GetValue(url.Length - 1).ToString()), SLTWidth, SLTHeight, ThumbnailMode.Width);
                    }
                }
            }
            
return tmp;
        }

        
/// <summary>
        
/// 上传文件
        
/// </summary>
        
/// <remarks>上传文件</remarks>
        
/// <param name="upFileControl">上传控件名称</param>
        
/// <param name="ReName">是否随机重命名文件</param>
        
/// <param name="CreatDirectory">是否创建一个和当前时间对应的文件夹</param>
        
/// <param name="CreateSLT">是否创建缩略图</param>
        
/// <param name="AddWaterImg">是否添加水印文字</param>
        
/// <param name="page">页面Page对象</param>
        
/// <returns>返回上传的文件名</returns>
        public string FileSave(FileUpload upFileControl, bool ReName, bool CreatDirectory, bool CreateSLT, bool AddWaterImg,Page page)
        {
            
string tmp = "";
            
string CreateFileUrl = "";
            
string CreateDir = "";
            
if (AddWaterImg)
            {
                
this.UploadPath = this.UploadPath + "temp/";
                tmp 
= FileSave(upFileControl, ReName, CreatDirectory, CreateSLT, page);
                CreateFileUrl 
= tmp.Replace("temp/""");
                CreateDir 
= CreateFileUrl.Substring(0, CreateFileUrl.LastIndexOf("/"+ 1);
                
if (!Directory.Exists(HttpContext.Current.Server.MapPath(CreateDir)))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(CreateDir));
                }
                FileInfo obj_File 
= new FileInfo(HttpContext.Current.Server.MapPath(tmp));
                
if (obj_File.Extension == ".jpg" || obj_File.Extension == ".gif" || obj_File.Extension == ".png" || obj_File.Extension == ".bmp")
                {
                    
if (this.WaterText.Length > 0)
                    {
                        
if (this.WaterFile.Length == 0)
                        {
                            AddWater(HttpContext.Current.Server.MapPath(tmp), HttpContext.Current.Server.MapPath(CreateFileUrl));
                            File.Delete(HttpContext.Current.Server.MapPath(tmp));
                        }
                        
else
                        {
                            AddWaterPic(HttpContext.Current.Server.MapPath(tmp), HttpContext.Current.Server.MapPath(CreateFileUrl), HttpContext.Current.Server.MapPath(
this.WaterFile));
                            File.Delete(HttpContext.Current.Server.MapPath(tmp));
                        }
                    }
                }
            }
            
return CreateFileUrl;
        }
        
#endregion

        
/// <summary>
        
/// 上传事件错误消息提示
        
/// </summary>
        
/// <param name="Msg">错误消息</param>
        
/// <param name="page">页面Page对象</param>
        private void UploadMsg(string Msg,Page page)
        {
            JavaScriptHelper.AlertWindow(Msg, page);
        }

        
#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, ThumbnailMode 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;

            
switch (Convert.ToInt32(mode))
            {
                
case 2://指定高宽缩放(可能变形)                
                    break;
                
case 1://指定宽,高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    
break;
                
case 0://指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    
break;
                
case 3://指定高宽裁减(不变形)                
                    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;
                
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(00, 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
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        
#endregion


        
#region 在图片上增加水印
        
/// <summary>
        
/// 在图片上增加文字水印
        
/// </summary>
        
/// <param name="Path">原服务器图片路径</param>
        
/// <param name="newPath">生成的带文字水印的图片路径</param>
        protected void AddWater(string Path, string newPath)
        {
            System.Drawing.Image image 
= System.Drawing.Image.FromFile(Path);
            
try
            {
                System.Drawing.Graphics g 
= System.Drawing.Graphics.FromImage(image);
                g.DrawImage(image, 
00, image.Width, image.Height);
                System.Drawing.Font f 
= new System.Drawing.Font("宋体"12);
                System.Drawing.Brush b 
= new System.Drawing.SolidBrush(System.Drawing.ColorTranslator.FromHtml("Black"));

                
int x, y;
                x 
= 100;
                y 
= 100;
                g.DrawString(
this.WaterText, f, b, x, y);
                g.Dispose();
                image.Save(newPath);
                image.Dispose();
            }
            
catch
            {
                image.Save(newPath);
                image.Dispose();
            }
        }


        
/// <summary>
        
/// 在图片上生成图片水印
        
/// </summary>
        
/// <param name="Path">原服务器图片路径</param>
        
/// <param name="Path_syp">生成的带图片水印的图片路径</param>
        
/// <param name="Path_sypf">水印图片路径</param>
        protected void AddWaterPic(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), 00, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();

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


        
#region 对应文件扩展名和相应文件头编码模型
        
/// <summary>
        
/// 对应文件扩展名和相应文件头编码!
        
/// </summary>
        
/// <remarks>对应文件扩展名和相应文件头编码!</remarks>
        private class FileExtension
        {

            
/// <param name="Extension">扩展名</param>
            
/// <param name="HeadCode">头部编码</param>
            public FileExtension(string Extension, string HeadCode)
            {
                
this.Extension = Extension;
                
this.HeadCode = HeadCode;
            }

            
/// <summary>
            
/// 扩展名
            
/// </summary>
            public string Extension
            {
                
get;
                
set;
            }

            
/// <summary>
            
/// 头部编码
            
/// </summary>
            public string HeadCode
            {
                
get;
                
set;
            }
        }
        
#endregion
    }
}

 

posted on 2010-03-25 15:57  bluesky  阅读(392)  评论(0编辑  收藏  举报