代码改变世界

C#文件上传类

2005-06-08 12:30  张剑  阅读(877)  评论(0编辑  收藏  举报

//设定上传文件的保存路径
string strSaveDir = "./Uploadface/";
string strName = FaceUpload.PostedFile.FileName;
//取得文件名(抱括路径)里最后一个"."的索引
int intExt = strName.LastIndexOf(".");
     
//取得文件扩展名
string strExt = strName.Substring(intExt);
     
//这里自动根据日期和文件大小不同为文件命名,确保文件名不重复
DateTime datNow = DateTime.Now;
strName = datNow.DayOfYear.ToString() + FaceUpload.PostedFile.ContentLength.ToString() + strExt;
     
string strNewName = "ADV"+datNow.DayOfYear.ToString() + FaceUpload.PostedFile.ContentLength.ToString() + strExt;
string strPath=strSaveDir + strNewName;
     
//上传文件的类型
     
if (strExt == ".jpg" || strExt == ".gif")
{
 //保存文件到你所要的目录,这里是IIS根目录下的upload目录.你可以改变.
 //注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里"\"必须用"\\"代替
 string path = Server.MapPath(strSaveDir + strName);
 FaceUpload.PostedFile.SaveAs(path);

 string newPath =Server.MapPath(strSaveDir + strNewName);

 /* 文字水印
 System.Drawing.Image image = System.Drawing.Image.FromFile(path);
 Graphics g = Graphics.FromImage(image);
 g.DrawImage(image, 0, 0, image.Width, image.Height);
 Font f = new Font("Verdana", 7);
 Brush b = new SolidBrush(Color.White);
 string addText = "ADVBBS.COM";
 g.DrawString(addText, f, b, 2, 2);
 g.Dispose();
 */
 //图片水印
 System.Drawing.Image image = System.Drawing.Image.FromFile(path);
 System.Drawing.Image copyImage = System.Drawing.Image.FromFile( Server.MapPath(".") + "/Alex.gif");
 Graphics g = Graphics.FromImage(image);
 g.DrawImage(copyImage, new Rectangle(image.Width-copyImage.Width, image.Height-copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
 g.Dispose();
 
 strResult=strPath;
 image.Save(newPath);
 image.Dispose();
 
 if(File.Exists(path))
 {
  File.Delete(path);
 }
}
else
{
Response.Redirect("?out=error&id=601");
}