本文通过前台file控件上传文件到虚拟目录当中,其中还有图片的上传
public class UploadHelper
{
public UploadHelper()
{ }
public UploadHelper(HttpPostedFile _postFile)
{
this._postFile = _postFile;
Init();
}
#region 属性和字段
private string _fileFullName = string.Empty;
private string _fileNameNoExt = string.Empty;
public string FileNameNoExt
{
get { return _fileNameNoExt; }
set { _fileNameNoExt = value; }
}
private string _fileExt = string.Empty;
private int _fileLength = 0;
//设置上传文件大小的单位1024*1024B=1M
private const int UNIT = 1024 * 1024;
private HttpPostedFile _postFile = null;
/// <summary>
/// 设置文件上传的控件对象(只写)
/// </summary>
public HttpPostedFile PostedFile
{
set
{
this._postFile = value;
Init();
}
}
private int _maxLength = 1;
/// <summary>
/// 设置上传文件的最大长度(默认1M)(单位MB)(只写)
/// </summary>
public int MaxLength
{
set
{
if (value <= 0)
{
value = 1;
}
_maxLength = value;
}
}
private FileType[] _allowUploadFileTypes = {
//FileType.GIF,
FileType.JPG,
//FileType.PNG,
//FileType.BMP,
};
/// <summary>
/// 设置允许上传的文件类型,(默认为JPG)(只写)
/// </summary>
public FileType[] AllowUploadFileTypes
{
set { this._allowUploadFileTypes = value; }
}
private string _savePath = HttpContext.Current.Server.MapPath(@"~/UploadFiles");
/// <summary>
/// 设置文件保存的路径(只读),默认在虚拟目录~/UploadFiles下
/// </summary>
public string SavePath
{
set
{
value = HttpContext.Current.Server.MapPath(value);
try
{
if (!Directory.Exists(value))
{
Directory.CreateDirectory(value);
}
}
catch
{
throw new Exception("创建上传文件路径异常!~~");
}
this._savePath = value;
}
}
/// <summary>
/// 保存在磁盘路径 【非项目本身路径】
/// </summary>
/// <param name="absloutAddress"></param>
/// <returns></returns>
public string SaveDiskPath(string absloutAddress)
{
return _savePath = absloutAddress;
}
private string _saveNameNotExt = string.Empty;
/// <summary>
/// 设置保存文件的名称(不带扩展名),一旦指定其他命名方式就失效,如果有重名的文件会直接覆盖
/// </summary>
public string SaveNameNotExt
{
set
{
this._saveNameNotExt = value;
}
}
private string _returnFileName = string.Empty;
/// <summary>
/// 获取文件上传成功后的保存在服务器上的文件名不带路径(统一返回的是原始生成的文件名)(只读)
/// </summary>
public string ReturnFileName
{
get { return _returnFileName; }
}
private SaveFileNameType _saveNameType = SaveFileNameType.Random;
/// <summary>
/// 设置上传的文件保存的文件名类型(只写,默认为Random)
/// </summary>
public SaveFileNameType SaveNameType
{
set { this._saveNameType = value; }
}
private ImageType _uploadImageType = ImageType.OnlyNormal;
/// <summary>
/// 设置上传的图片生成缩略图类型(只写,默认为只生成一张正常图OnlyNormal)
/// </summary>
public ImageType UploadImageType
{
set { this._uploadImageType = value; }
}
private Size _smallImageSize = new Size(100, 100);
/// <summary>
/// 缩略图的大小(只写,默认100*100)
/// </summary>
public Size SmallImageSize
{
set { this._smallImageSize = value; }
}
private Size _normalImageSize = new Size(360, 360);
/// <summary>
/// 正常图的大小(只写,默认360*360)
/// </summary>
public Size NormalImageSize
{
set { this._normalImageSize = value; }
}
private bool _isShowWater = false;
/// <summary>
/// 是否设置上传图片的水印图(只写,默认为无)
/// </summary>
public bool IsShowWater
{
set { _isShowWater = value; }
}
private string _waterImage = string.Empty;
/// <summary>
/// 设置文件保存的路径(只读),默认在虚拟目录~/UploadFiles下
/// </summary>
public string WaterImage
{
set
{
value = HttpContext.Current.Server.MapPath(value);
if (!File.Exists(value))
{
throw new Exception("水印图片不存在!~~");
}
this._waterImage = value;
}
}
string _msg = string.Empty;
/// <summary>
/// 返回上传相关的信息(只读)
/// </summary>
public string Msg
{
get { return _msg; }
}
#endregion
#region 初始化类的成员变量
/// <summary>
/// 设置HttpPostedFile对象之后初始化类的成员变量
/// </summary>
private void Init()
{
this._fileFullName = this._postFile.FileName;
if (!string.IsNullOrEmpty(_fileFullName))
{
this._fileNameNoExt = this._fileFullName.Substring(0, this._fileFullName.LastIndexOf('.'));
}
this._fileExt = Path.GetExtension(this._fileFullName);
this._fileLength = this._postFile.ContentLength;
}
#endregion
#region 上传图片
public bool UploadImage()
{
return UploadImage(this._uploadImageType, this._allowUploadFileTypes);
}
public bool UploadImage(ImageType _imageType)
{
return UploadImage(_imageType, this._allowUploadFileTypes);
}
public bool UploadImage(params FileType[] _fileTypes)
{
return UploadImage(this._uploadImageType, _fileTypes);
}
public bool UploadImage(ImageType _imageType, params FileType[] _fileTypes)
{
//if (IsValidate(_fileTypes))
if (1 == 1)
{
this._returnFileName = GetSaveName();
switch (_imageType)
{
case ImageType.OnlySmall:
this._fileNameNoExt = "S_" + this._returnFileName;
CreateImage(this._smallImageSize);
break;
case ImageType.OnlyNormal:
this._fileNameNoExt = "Z_" + this._returnFileName;
CreateImage(this._normalImageSize);
break;
case ImageType.OnlyOld:
this._fileNameNoExt = this._returnFileName;
CreateImage(new Size(0, 0));
break;
//this._fileNameNoExt = this._returnFileName;
//this._postFile.SaveAs(this.SavePath + "\\" + this._fileNameNoExt + this._fileExt);
//this._msg = "图片文件成功,已经保存到服务器上目录下!\\n";
//break;
case ImageType.SmallAndNormal:
this._fileNameNoExt = "Z_" + this._returnFileName;
CreateImage(this._smallImageSize);
this._fileNameNoExt = "S_" + this._fileNameNoExt.Substring(2, this._fileNameNoExt.Length - 2);
CreateImage(this._normalImageSize);
break;
case ImageType.SmallAndOld:
//this._fileNameNoExt = this._returnFileName;
//this._postFile.SaveAs(this.SavePath + "\\" + this._fileNameNoExt + this._fileExt);
//this._msg = "图片文件成功,已经保存到服务器上目录下!\\n";
this._fileNameNoExt = this._returnFileName;
CreateImage(new Size(0, 0));
this._fileNameNoExt = this._fileNameNoExt + "_s";
CreateImage(this._smallImageSize);
break;
case ImageType.NormalAndOld:
//this._fileNameNoExt = this._returnFileName;
//this._postFile.SaveAs(this.SavePath + "\\" + this._fileNameNoExt + this._fileExt);
//this._msg = "图片文件成功,已经保存到服务器上目录下!\\n";
this._fileNameNoExt = this._returnFileName;
CreateImage(new Size(0, 0));
this._fileNameNoExt = this._fileNameNoExt + "_n";
CreateImage(this._normalImageSize);
break;
case ImageType.SmallAndNormalAndOld:
//this._fileNameNoExt = this._returnFileName;
//this._postFile.SaveAs(this.SavePath + "\\" + this._fileNameNoExt + this._fileExt);
//this._msg = "图片文件成功,已经保存到服务器上目录下!\\n";
this._fileNameNoExt = this._returnFileName;
CreateImage(new Size(0, 0));
this._fileNameNoExt = this._fileNameNoExt + "_s";
CreateImage(this._smallImageSize);
this._fileNameNoExt = this._fileNameNoExt.Substring(0, (this._fileNameNoExt.Length - 1)) + "n";
CreateImage(this._normalImageSize);
break;
default:
return false;
}
this._returnFileName += this._fileExt;
return true;
}
else
{
return false;
}
}
#endregion
#region 生成图片和水印
private void CreateImage(Size _newSize)
{
Image _oldImg = Image.FromStream(this._postFile.InputStream);
//只生成原图的情况下
if ((_newSize.Width == 0) || (_newSize.Height == 0))
{
_newSize.Width = _oldImg.Width;
_newSize.Height = _oldImg.Height;
try
{
if (this._isShowWater)
{
_oldImg = CreateWaterImage(_oldImg);
}
_oldImg.Save(this._savePath + "\\" + this._fileNameNoExt + _fileExt);
}
catch
{
throw new Exception("原图写入到磁盘失败!~~");
}
}
else
{
//按比例计算出缩略图的宽度和高度
if (_oldImg.Width >= _oldImg.Height)
{
//等比设定高度 缩略图高度 =(原图高度*缩略图的宽度)/原图宽度
_newSize.Height = (int)Math.Floor(Convert.ToDouble(_oldImg.Height) *
(Convert.ToDouble(_newSize.Width) / Convert.ToDouble(_oldImg.Width)));
}
else
{
//等比设定宽度 缩略图宽度=(原图宽度*缩略图高度)/原图高度
_newSize.Width = (int)Math.Floor(Convert.ToDouble(_oldImg.Width) *
(Convert.ToDouble(_newSize.Height) / Convert.ToDouble(_oldImg.Height)));
}
//生成缩略图
Image _newImage = new Bitmap(_newSize.Width, _newSize.Height);
Graphics g = Graphics.FromImage(_newImage);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);
//绘制缩略图(原图对象,缩略图矩阵,原图矩阵,绘制填充方式(像素点填充))
g.DrawImage(_oldImg, new System.Drawing.Rectangle(new Point(0, 0), _newSize),
new System.Drawing.Rectangle(0, 0, _oldImg.Width, _oldImg.Height),
System.Drawing.GraphicsUnit.Pixel);
//保存缩略图
try
{
if (this._isShowWater)
{
_newImage = CreateWaterImage(_newImage);
}
_newImage.Save(this._savePath + "\\" + this._fileNameNoExt + _fileExt);
}
catch
{
throw new Exception("裁减图片失败或者写入到磁盘失败!~~");
}
}
}
/// <summary>
/// 生成图片水印
/// </summary>
/// <param name="_oldImage">图片对象</param>
/// <returns>生成水印之后的对象</returns>
private Image CreateWaterImage(Image _img)
{
if (this._isShowWater)
{
Image _waterImg = Image.FromFile(this._waterImage);
Graphics wg = Graphics.FromImage(_img);
wg.DrawImage(_waterImg, new System.Drawing.Rectangle(
_img.Width - _waterImg.Width - 20, _img.Height - _waterImg.Height - 10,
_waterImg.Width, _waterImg.Height), 0, 0, _waterImg.Width, _waterImg.Height,
System.Drawing.GraphicsUnit.Pixel);
}
return _img;
}
#endregion
#region 上传文件
/// <summary>
/// 上传
/// </summary>
/// <returns></returns>
public bool UploadSeehealtFile()
{
try
{
this._fileNameNoExt = GetSaveName();
this._postFile.SaveAs(this._savePath + "\\" + this._fileNameNoExt + this._fileExt);
this._msg = "上传文件成功,已经保存到服务器上目录下!\\n";
this._returnFileName = this._fileNameNoExt + this._fileExt;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 上传文件,上传之前应对许可上传的文件类型进行定义(FileExtensions属性)
/// </summary>
/// <returns>文件是否上传成功</returns>
public bool UploadFile()
{
return UploadFile(this._allowUploadFileTypes);
}
/// <summary>
/// 直接上传文件
/// </summary>
/// <param name="_fileTypes">允许上传文件的类型列表</param>
/// <returns>文件是否上传成功</returns>
public bool UploadFile(params FileType[] _fileTypes)
{
if (IsValidate(_fileTypes))
{
this._fileNameNoExt = GetSaveName();
this._postFile.SaveAs(this._savePath + "\\" + this._fileNameNoExt + this._fileExt);
this._msg = "上传文件成功,已经保存到服务器上目录下!\\n";
this._returnFileName = this._fileNameNoExt + this._fileExt;
return true;
}
else
{
return false;
}
}
#endregion
#region 获取文件名
/// <summary>
/// 获取保存的文件名(根据设置的保存的文件名类型)
/// </summary>
/// <returns>文明名,不带扩展名</returns>
private string GetSaveName()
{
if (string.IsNullOrEmpty(this._saveNameNotExt))
{
if (this._saveNameType == SaveFileNameType.Random)
{
return GetRandomStr();
}
else if (this._saveNameType == SaveFileNameType.Old)
{
//指定文件名,如果文件存在,不覆盖,新建一个相似名称文件
if (File.Exists(this._savePath + "\\" + this._fileNameNoExt + _fileExt))
{
Random r = new Random();
int i = r.Next(1000);
return this._fileNameNoExt + "_" + i.ToString();
}
else
{
return this._fileNameNoExt;
}
}
else
{
return this._fileNameNoExt;
}
}
else
{
return _saveNameNotExt;
}
}
/// <summary>
/// 获取日期时间格式的名称带毫秒和10000随机数
/// </summary>
/// <returns>如:20111006,115236,256,999</returns>
private string GetRandomStr()
{
StringBuilder sb = new StringBuilder();
string strName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
Random r = new Random();
int i = r.Next(10000);
sb.Append(strName);
sb.Append(i.ToString());
return sb.ToString();
}
#endregion
#region 判断要上传的文件是否合法
/// <summary>
/// 判断要上传的文件是否合法
/// </summary>
/// <param name="fileExt">文件的类型枚举数组</param>
/// <returns>是否合法</returns>
public bool IsValidate(params FileType[] _fileTypes)
{
if (this._fileLength < 1)
{
this._msg += "你没有要上传的文件或者文件为空!\\n";
return false;
}
if (this._fileLength > (this._maxLength * UNIT))
{
this._msg += string.Format("你上传的文件过大,只允许上传{0}M!\\n", this._maxLength);
return false;
}
string _fileclass = string.Empty;
byte _buffer;
byte[] _fileArray = new byte[2];
this._postFile.InputStream.Read(_fileArray, 0, 2);
using (MemoryStream ms = new MemoryStream(_fileArray))
{
using (BinaryReader br = new System.IO.BinaryReader(ms))
{
try
{
_buffer = br.ReadByte();
_fileclass = _buffer.ToString();
_buffer = br.ReadByte();
_fileclass += _buffer.ToString();
}
catch
{
this._msg += "验证文件类型失败,为了保护系统安全,请重新上传\\n";
return false;
}
}
ms.Dispose();
}
int _fileType;
foreach (FileType ft in _fileTypes)
{
int.TryParse(_fileclass, out _fileType);
if (_fileType == (int)ft)
{
return true;
}
}
this._msg += "你上传的文件类型不合法!\\n";
return false;
}
#endregion
#region 生成图片的类型
/// <summary>
/// 生成图片的类型(缩略图类型)(如果要生成缩略图或正常图请设置图片尺寸)
/// </summary>
public enum ImageType
{
/// <summary>
/// 只上传缩略图
/// </summary>
OnlySmall,
/// <summary>
/// 只上传正常图
/// </summary>
OnlyNormal,
/// <summary>
/// 只上传原始图
/// </summary>
OnlyOld,
/// <summary>
/// 上传缩略图和正常图
/// </summary>
SmallAndNormal,
/// <summary>
/// 上传缩略图和原始图
/// </summary>
SmallAndOld,
/// <summary>
/// 上传正常图和原始图
/// </summary>
NormalAndOld,
/// <summary>
/// 上传缩略图和正常图和原始图
/// </summary>
SmallAndNormalAndOld,
/// <summary>
/// 2张缩略图
/// </summary>
TwoSmall,
}
#endregion
#region 保存的文件名的类型枚举
/// <summary>
/// 上传保存的文件名的类型
/// </summary>
public enum SaveFileNameType : byte
{
/// <summary>
/// 使用随机生成(格式:YYYYMMDDHHMMSSFFFF****)
/// </summary>
Random,
/// <summary>
/// 如果上传的文件名存在,就覆盖存在的文件,不存在就以原始名称保存
/// </summary>
Cover,
/// <summary>
/// 如果上传的文件名存在,在原始文件名基础上加上一个随机数保存,不存在原始名保存
/// </summary>
Old
}
#endregion
#region 文件类型枚举
public enum FileType
{
JPG = 255216,
GIF = 7173,
PNG = 13780,
SWF = 6787,
RAR = 8297,
ZIP = 8075,
BMP = 6677,
TXT = 99120,
DOC = 208207,
// 255216 jpg;
// 7173 gif;
// 6677 bmp,
// 13780 png;
// 6787 swf
// 7790 exe dll,
// 8297 rar
// 8075 zip
// 55122 7z
// 6063 xml
// 6033 html
// 239187 aspx /txt_utf_8
// 117115 cs
// 119105 js
// 99120 txt
// 255254 unicode
}
#endregion
}