求教怎样上传文件
希望大家帮忙,先在此谢了!
/*---------------------------------------------
* 黑白之间
* gxian22@
* 最后修改日期:2008年9月9日21:39:41
*UploadFile ufud = new UploadFile();
*
* ufud.FileSize = 250;
* 默认为 200KB 如要上传大于6兆以上图片要在web.config 配置<system.web><httpRuntime maxRequestLength="10240"
executionTimeout="60"/></system.web>
*
*ufud.UploadFileList = "/UploadFiles"; //默认为 UploadFile 文件夹
*
*--------不压缩则不设置---------
*ufud.Reduce=1 //1为缩略图
*ufud.ImgHidth = 250;//缩略尺寸
*ufud.ImgWidth = 250;//缩略尺寸
*-------------------------------
*ufud.RewriteFileNameMode = 2;//更改上传文件名字有三种(0 原始的 不更改 ,1 全局唯一标识型,2 时间 ) 默认全局唯一标识型 类型
*ufud.FilesUploadExtension = ".gif,.jpg,.png,.html";
*ufud.FileUploads(Fil.PostedFile);// Fil(上传控件名称).PostedFile
*
*
*Response.Write(ufud.SucceedAndError)//返回成功或错误文字信息
*Response.Write(ufud.ErrorCode) //返回成功或错误代码 0成功 1文件太大 2文件太小 3格式不正确 4其他错误
*Response.Write(ufud.ReturnFilePath) //返回上传文件路径
---------------------------------------------*/
using System;
using
using System.Drawing;
namespace Common
{
/// <summary>
/// 支持上传缩略图、更改图片名、自定义上传文件格式和文件大小。
/// </summary>
public class UploadFile
{
private string uploadfilelist = "UploadFile";
private int userid = 0;
private int filesize = 200;//200K
private string filesuploadextension = ".gif,.jpg,.png";
private string returnfilepath = "--";
private string succeedanderror = null;
private int errorcode = 0;
private int rewritefilenamemode = 1;
private int imgheight = 120, imgwidth = 120;
private int reduce = 0;
/// <summary>
/// 上传图片默认原始大小,1为缩略图同时你要设置缩略 宽:ImgWidth=?,高: ImgHidth=?
/// </summary>
public int Reduce
{
get { return reduce; }
set { reduce = value; }
}
/// <summary>
/// 图片缩略宽度大小 默认 120
/// </summary>
public int ImgWidth
{
get { return imgwidth; }
set { imgwidth = value; }
}
/// <summary>
/// 图片缩略高大小 默认 120
/// </summary>
public int ImgHidth
{
get { return imgheight; }
set { imgheight = value; }
}
/// <summary>
/// 上传文件存放目录
/// </summary>
public string UploadFileList
{
get { return uploadfilelist; }
set { uploadfilelist = value; }
}
/// <summary>
/// 更改上传文件名字有三种(0 原始的 不更改 ,1 全局唯一标识型,2 时间 ) 默认全局唯一标识型 类型
/// </summary>
public int RewriteFileNameMode
{
get { return rewritefilenamemode; }
set { rewritefilenamemode = value; }
}
/// <summary>
/// 上传用户ID
/// </summary>
public int UserID
{
get { return userid; }
set { userid = value; }
}
/// <summary>
/// 文件上传大小 默认为200K
/// </summary>
public int FileSize
{
get { return filesize; }
set { filesize = value; }
}
/// <summary>
/// 设置允许上传文件类型, 默认为(.gif,.jpg,.txt)
/// </summary>
public string FilesUploadExtension
{
get { return filesuploadextension; }
set { filesuploadextension = value; }
}
/// <summary>
/// 返回上传文件路径
/// </summary>
public string ReturnFilePath
{
get { return returnfilepath; }
set { returnfilepath = value; }
}
/// <summary>
/// 成功 或 错误信息
/// </summary>
public string SucceedAndError
{
get { return succeedanderror; }
set { succeedanderror = value; }
}
/// <summary>
/// 返回错误编号 0成功 1文件太大 2文件太小 3格式不正确 4其他错误
/// </summary>
public int ErrorCode
{
get { return errorcode; }
set { errorcode = value; }
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="HttpPflie">上传控件名称</param>
public void FileUploads(System.Web.HttpPostedFile HttpPflie)
{
System.Drawing.Image oriImg;//, newImg;
int ImageHeight, ImageWidth;
string strFileExt = (HttpPflie.FileName).ToString().ToLower(); //提取上传文件
扩展名。
if ("".Equals(strFileExt))
{
SucceedAndError = String.Format("不能上传的文件,允许上传格式({0})", FilesUploadExtension);
ErrorCode = 3;
ReturnFilePath = "--";
return;
}
int ifcheck = FilesUploadExtension.IndexOf(strFileExt.ToLower()); //是否为允许上传的格式
if (ifcheck < 0)
{
SucceedAndError = String.Format("不能上传的文件,允许上传格式{0}", FilesUploadExtension);
ErrorCode = 3;
ReturnFilePath = "--";
return;
}
int FileUploadSize = FilSize(HttpPflie.ContentLength); //上传文件大小
if (FileUploadSize <= 0)
{
SucceedAndError = "文件不得小于0KB";
ErrorCode = 2;
ReturnFilePath = "--";
return;
}
if (FileUploadSize >= FileSize)
{
SucceedAndError = String.Format("文件不得大于{0},您超过了{1}", Utils.FormatKBStr(FileSize),
Utils.FormatKBStr(FileUploadSize - FileSize));
ErrorCode = 1;
ReturnFilePath = "--";
return;
}
if (ifcheck >= 0 && FileUploadSize > 0 && FileUploadSize < FileSize)
{
string NewFileName = null, filelist = null;
//生成文件名
try
{
#region ----------生成上传文件名----------
switch (RewriteFileNameMode)
{
case 2://时间型文件名
DateTime date = DateTime.Now;
string FileName = date.Date.ToString("yyyy") + date.Date.ToString("MM") + date.Date.ToString
("dd");
FileName += date.ToString("HH") + date.ToString("mm") + date.ToString("ss");
Random rnd = new Random();
double rndNum = rnd.NextDouble() * 10000;
NewFileName = FileName + rndNum.ToString().Substring(0, rndNum.ToString().LastIndexOf(".")) +
strFileExt; //生成新的文件名
break;
case 1:
NewFileName = Guid.NewGuid().ToString("b") + strFileExt;
break;
case 0:
NewFileName = HttpPflie.FileName.Substring(HttpPflie.FileName.LastIndexOf("/") > -1 ?
HttpPflie.FileName.LastIndexOf("/") : HttpPflie.FileName.LastIndexOf("\\")).Replace("/", "").Replace("\\", "");
break;
}
#endregion
//创建文件夹 将上传的文件按月分开存放。
string datafile = Convert.ToDateTime(DateTime.Now).ToString("yyyy") + "-" + Convert.ToDateTime
(DateTime.Now).ToString("MM");
filelist = UploadFileList + "/" + datafile + "/" + strFileExt.Replace(".", "") + "/";
string path = System.Web.HttpContext.Current.Server.MapPath(filelist);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);//生成文件保存目录
#region ----------生成缩略图并上传----------
if (Reduce == 1 && HttpPflie.ContentType.Split('/')[0].Equals("image"))//HttpPflie.ContentType是否为
图片文件
{
oriImg = System.Drawing.Image.FromStream(HttpPflie.InputStream);
if (oriImg.Width / oriImg.Height >= ImgWidth / ImgHidth)
{
if (oriImg.Width > ImgHidth)
{
ImageWidth = ImgWidth;
ImageHeight = Convert.ToInt32(oriImg.Height * ImgWidth) / oriImg.Width;
}
else
{
ImageWidth = oriImg.Width;
ImageHeight = oriImg.Height;
}
}
else
{
if (oriImg.Height > ImgWidth)
{
ImageWidth = Convert.ToInt32(oriImg.Width * ImgHidth) / oriImg.Height;
ImageHeight = ImgHidth;
}
else
{
ImageWidth = oriImg.Width;
ImageHeight = oriImg.Height;
}
}
//----------------------高质量---------------------
Bitmap newImg = new Bitmap(ImageWidth, ImageHeight); //以缩略图的宽高
创建位图对象
Graphics g = Graphics.FromImage(newImg); //创建Graphics对
象,用于缩略图的图像的绘制
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //获取或设置与此
Graphics 对象关联的插补模式。指定高质量插值法。
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //指定高质量、低
速度呈现。
g.Clear(Color.Transparent); //清除整个绘图面
并以透明色填充。
g.DrawImage(System.Drawing.Image.FromStream(HttpPflie.InputStream), new Rectangle(0, 0,
ImageWidth, ImageHeight), new Rectangle(0, 0, oriImg.Width, oriImg.Height), GraphicsUnit.Pixel);//缩略图绘制
// newImg = oriImg.GetThumbnailImage(ImageWidth, ImageHeight, null, new System.IntPtr(0)); //低质
量
switch (strFileExt)
{
case ".jpg": newImg.Save(path + "/" + NewFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".gif": newImg.Save(path + "/" + NewFileName, System.Drawing.Imaging.ImageFormat.Gif);
break;
case ".png": newImg.Save(path + "/" + NewFileName, System.Drawing.Imaging.ImageFormat.Png);
break;
default: newImg.Save(path + "/" + NewFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
}
oriImg.Dispose();
newImg.Dispose();
}
#endregion
#region ----------原始尺寸图片上传----------
if (!HttpPflie.ContentType.Split('/')[0].Equals("image") || Reduce == 0)
{
path = path + "/" + NewFileName;
HttpPflie.SaveAs(path);
}
#endregion
SucceedAndError = "文件上传成功";
ErrorCode = 0;
ReturnFilePath = filelist + NewFileName;
}
catch (Exception e){
SucceedAndError = e.Message;
ErrorCode = 4;
}
finally{
//break;
}
}
}
private static int FilSize(int imgSize)
{
return ((imgSize / 1024) * 100) / 100;
}
}
}