Upload.aspx
<
form
id
="PostUp"
method
="post"
encType
="multipart/form-data"
runat
="server"
>
文件路径: < input id ="PostUpFile" type ="file" size ="30" name ="PostUpFile" runat ="server" >
< asp:button id ="btn_PostUp" runat ="server" Text ="上传" Height ="20px" ></ asp:button >
</ form >
文件路径: < input id ="PostUpFile" type ="file" size ="30" name ="PostUpFile" runat ="server" >
< asp:button id ="btn_PostUp" runat ="server" Text ="上传" Height ="20px" ></ asp:button >
</ form >
Upload.aspx.cs
using
System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Text;
namespace Sample.Upload_Sample
{
/**//// <summary>
/// Upload 的摘要说明。
/// </summary>
public class Upload : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputFile PostUpFile;
protected System.Web.UI.WebControls.Button btn_PostUp;
long FileMaxSize = Convert.ToInt32(ConfigurationSettings.AppSettings["FileMaxSize"]);
SqlConnection Conn;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btn_PostUp.Click += new System.EventHandler(this.btn_PostUp_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btn_PostUp_Click(object sender, System.EventArgs e)
{
string fName,FileName,SaveName,Extension,PrewImagName,PrewImagNamePath;
int CheckFileType;
int FontSize;
long FileSize;
FontSize = 20; //字符水印字体大小
string addText = "字符水印"; //字符水印内容
if(PostUpFile.PostedFile.FileName.Trim()!="") //上传文件名非空
{
try
{
CreateDirectory();
fName = PostUpFile.PostedFile.FileName.ToString();
Extension = Path.GetExtension(PostUpFile.PostedFile.FileName).ToLower();
FileSize = PostUpFile.PostedFile.ContentLength;
//判断文件类型:0=其它,1=图片,2=FLASH,3=音乐,4=电影
switch (Extension)
{
case ".gif":CheckFileType = 1;break;
case ".jpg":CheckFileType = 1;break;
case ".jpeg":CheckFileType = 1;break;
case ".png":CheckFileType = 1;break;
case ".bmp":CheckFileType = 1;break;
case ".swf":CheckFileType = 2;break;
case ".swi":CheckFileType = 2;break;
case ".mid":CheckFileType = 3;break;
case ".wav":CheckFileType = 3;break;
case ".mp3":CheckFileType = 3;break;
case ".avi":CheckFileType = 4;break;
case ".ra":CheckFileType = 4;break;
case ".rm":CheckFileType = 4;break;
case ".mpg":CheckFileType = 4;break;
case ".mpeg":CheckFileType = 4;break;
case ".asf":CheckFileType = 4;break;
case ".wov":CheckFileType = 4;break;
default:CheckFileType = 0;break;
}
//检查文件类型及大小
if(Extension == ".asp" || Extension == ".aspx" || Extension == ".php" || Extension == ".jsp" || Extension == ".asa" )
{
ShowMsg("上传文件类别超出限定范围!");
return;
}
if(FileSize > FileMaxSize)
{
ShowMsg("上传文件大小超出范围!");
return;
}
FileName = CreateFileName() + Extension;
SaveName = "UploadFiles/" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "/" + FileName;
try
{
PostUpFile.PostedFile.SaveAs(CreateDirectory() + "\\" + FileName);
}
catch(IOException)
{
ShowMsg("上传失败");
return;
}
//如果文件是"bmp,jpg,jpeg,gif"则生成预览图并加上水印
if (Extension == ".gif" || Extension == ".jpg" || Extension == ".jpeg" || Extension == ".bmp" || Extension == ".png")
{
//1.加文字水印,注意,这里的代码和以下加图片水印的代码不能共存
System.Drawing.Image image = System.Drawing.Image.FromFile(CreateDirectory() + "\\" + FileName);
Graphics g = Graphics.FromImage(image);
g.DrawImage(image, 0, 0, image.Width, image.Height);
Font f = new Font("迷你简粗倩", FontSize, System.Drawing.FontStyle.Bold);
Brush b = new SolidBrush(Color.White);
g.DrawString(addText, f, b, 5, 5);
g.Dispose();
//2.加图片水印
/**//*
System.Drawing.Image image = System.Drawing.Image.FromFile(CreateDirectory() + "\\" + FileName);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile( Server.MapPath("..//Images//") + "CopyRight.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();
*/
//预览图地址
PrewImagName = "PrewImages/" + "Prew_" + FileName;
PrewImagNamePath = Server.MapPath("PrewImages\\").ToString() + "Prew_" + FileName;
image.Save(PrewImagNamePath);
image.Dispose();
}
else
{
PrewImagName = "none";
}
//保存文件信息到数据库
string strSQL = "Insert into UploadFiles (f_joindate,f_filename,f_savename,f_prewimg,f_type,f_extname,f_size) Values("
+ "'" + DateTime.Now.ToString() + "',"
+ "'" + FileName + "',"
+ "'" + SaveName + "',"
+ "'" + PrewImagName + "',"
+ CheckFileType + ","
+ "'" + Extension.Replace(".","").ToString().Trim() + "',"
+ FileSize + ")";
Conn = new SqlConnection(var.StrConn);
SqlCommand myCmd = new SqlCommand(strSQL,Conn);
Conn.Open();
myCmd.ExecuteNonQuery();
myCmd.Dispose();
Conn.Close();
Response.Write ("<script language='javascript'>alert('上传文件成功!');location='Default.aspx';</script>");
}
catch(Exception er)
{
ShowMsg(er.Message);
}
}
}
//检查目录存在并添加新目录
private string CreateDirectory()
{
string Path,Dic;
Dic = Server.MapPath("UploadFiles\\").ToString() + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString();
Path = @Dic;
try
{
// 检查目录是否已经创建.
if (Directory.Exists(Path))
{
return Dic;
}
// 尝试创建目录
DirectoryInfo di = Directory.CreateDirectory(Path);
}
catch (Exception e)
{
ShowMsg("建立日期文件夹出错!");
}
finally {}
return Dic;
}
//创建文件名
private string CreateFileName()
{
Random rnd = new Random();
StringBuilder sb = new StringBuilder();
int i;
for (i=0;i<=5;i++)
{
sb.Append(rnd.Next(0,9).ToString());
}
string EXT = sb.ToString();
string FileName = "Yandd_" + DateTime.Now.Year.ToString()
+ DateTime.Now.Month.ToString()
+ DateTime.Now.Day.ToString()
+ DateTime.Now.Hour.ToString()
+ DateTime.Now.Minute.ToString()
+ DateTime.Now.Second.ToString()
+ EXT;
return FileName;
}
//发现错误Alert
private void ShowMsg(string err)
{
string Str;
Str="<script language='javascript'>";
Str+=" alert('" +err + "')";
Str+="</script>";
Response.Write ( Str );
}
}
}
// 检查文件类型MIME
// 上传文件类型
// 常见文件的MIME类型
// GIF文件 "image/gif"
// BMP文件 "image/bmp"
// JPG文件 "image/jpeg"
// PNG文件 "image/x-png"
// ICO文件 "image/x-icon"
// zip文件 "application/x-zip-compressed"
// DOC文件 "application/msword"
// 文本文件 "text/plain"
// HTML文件 "text/html"
// 一般文件 "application/octet-stream"
// SWF文件 "application/x-shockwave-flash"
// RAR文件 "application/octet-stream"
// MDB文件 "application/msaccess"
// 所有图片检验例句 "fType.Substring(0,5)"
// 其他文件检验例句 "fType.ToString()"
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Text;
namespace Sample.Upload_Sample
{
/**//// <summary>
/// Upload 的摘要说明。
/// </summary>
public class Upload : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputFile PostUpFile;
protected System.Web.UI.WebControls.Button btn_PostUp;
long FileMaxSize = Convert.ToInt32(ConfigurationSettings.AppSettings["FileMaxSize"]);
SqlConnection Conn;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btn_PostUp.Click += new System.EventHandler(this.btn_PostUp_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btn_PostUp_Click(object sender, System.EventArgs e)
{
string fName,FileName,SaveName,Extension,PrewImagName,PrewImagNamePath;
int CheckFileType;
int FontSize;
long FileSize;
FontSize = 20; //字符水印字体大小
string addText = "字符水印"; //字符水印内容
if(PostUpFile.PostedFile.FileName.Trim()!="") //上传文件名非空
{
try
{
CreateDirectory();
fName = PostUpFile.PostedFile.FileName.ToString();
Extension = Path.GetExtension(PostUpFile.PostedFile.FileName).ToLower();
FileSize = PostUpFile.PostedFile.ContentLength;
//判断文件类型:0=其它,1=图片,2=FLASH,3=音乐,4=电影
switch (Extension)
{
case ".gif":CheckFileType = 1;break;
case ".jpg":CheckFileType = 1;break;
case ".jpeg":CheckFileType = 1;break;
case ".png":CheckFileType = 1;break;
case ".bmp":CheckFileType = 1;break;
case ".swf":CheckFileType = 2;break;
case ".swi":CheckFileType = 2;break;
case ".mid":CheckFileType = 3;break;
case ".wav":CheckFileType = 3;break;
case ".mp3":CheckFileType = 3;break;
case ".avi":CheckFileType = 4;break;
case ".ra":CheckFileType = 4;break;
case ".rm":CheckFileType = 4;break;
case ".mpg":CheckFileType = 4;break;
case ".mpeg":CheckFileType = 4;break;
case ".asf":CheckFileType = 4;break;
case ".wov":CheckFileType = 4;break;
default:CheckFileType = 0;break;
}
//检查文件类型及大小
if(Extension == ".asp" || Extension == ".aspx" || Extension == ".php" || Extension == ".jsp" || Extension == ".asa" )
{
ShowMsg("上传文件类别超出限定范围!");
return;
}
if(FileSize > FileMaxSize)
{
ShowMsg("上传文件大小超出范围!");
return;
}
FileName = CreateFileName() + Extension;
SaveName = "UploadFiles/" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "/" + FileName;
try
{
PostUpFile.PostedFile.SaveAs(CreateDirectory() + "\\" + FileName);
}
catch(IOException)
{
ShowMsg("上传失败");
return;
}
//如果文件是"bmp,jpg,jpeg,gif"则生成预览图并加上水印
if (Extension == ".gif" || Extension == ".jpg" || Extension == ".jpeg" || Extension == ".bmp" || Extension == ".png")
{
//1.加文字水印,注意,这里的代码和以下加图片水印的代码不能共存
System.Drawing.Image image = System.Drawing.Image.FromFile(CreateDirectory() + "\\" + FileName);
Graphics g = Graphics.FromImage(image);
g.DrawImage(image, 0, 0, image.Width, image.Height);
Font f = new Font("迷你简粗倩", FontSize, System.Drawing.FontStyle.Bold);
Brush b = new SolidBrush(Color.White);
g.DrawString(addText, f, b, 5, 5);
g.Dispose();
//2.加图片水印
/**//*
System.Drawing.Image image = System.Drawing.Image.FromFile(CreateDirectory() + "\\" + FileName);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile( Server.MapPath("..//Images//") + "CopyRight.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();
*/
//预览图地址
PrewImagName = "PrewImages/" + "Prew_" + FileName;
PrewImagNamePath = Server.MapPath("PrewImages\\").ToString() + "Prew_" + FileName;
image.Save(PrewImagNamePath);
image.Dispose();
}
else
{
PrewImagName = "none";
}
//保存文件信息到数据库
string strSQL = "Insert into UploadFiles (f_joindate,f_filename,f_savename,f_prewimg,f_type,f_extname,f_size) Values("
+ "'" + DateTime.Now.ToString() + "',"
+ "'" + FileName + "',"
+ "'" + SaveName + "',"
+ "'" + PrewImagName + "',"
+ CheckFileType + ","
+ "'" + Extension.Replace(".","").ToString().Trim() + "',"
+ FileSize + ")";
Conn = new SqlConnection(var.StrConn);
SqlCommand myCmd = new SqlCommand(strSQL,Conn);
Conn.Open();
myCmd.ExecuteNonQuery();
myCmd.Dispose();
Conn.Close();
Response.Write ("<script language='javascript'>alert('上传文件成功!');location='Default.aspx';</script>");
}
catch(Exception er)
{
ShowMsg(er.Message);
}
}
}
//检查目录存在并添加新目录
private string CreateDirectory()
{
string Path,Dic;
Dic = Server.MapPath("UploadFiles\\").ToString() + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString();
Path = @Dic;
try
{
// 检查目录是否已经创建.
if (Directory.Exists(Path))
{
return Dic;
}
// 尝试创建目录
DirectoryInfo di = Directory.CreateDirectory(Path);
}
catch (Exception e)
{
ShowMsg("建立日期文件夹出错!");
}
finally {}
return Dic;
}
//创建文件名
private string CreateFileName()
{
Random rnd = new Random();
StringBuilder sb = new StringBuilder();
int i;
for (i=0;i<=5;i++)
{
sb.Append(rnd.Next(0,9).ToString());
}
string EXT = sb.ToString();
string FileName = "Yandd_" + DateTime.Now.Year.ToString()
+ DateTime.Now.Month.ToString()
+ DateTime.Now.Day.ToString()
+ DateTime.Now.Hour.ToString()
+ DateTime.Now.Minute.ToString()
+ DateTime.Now.Second.ToString()
+ EXT;
return FileName;
}
//发现错误Alert
private void ShowMsg(string err)
{
string Str;
Str="<script language='javascript'>";
Str+=" alert('" +err + "')";
Str+="</script>";
Response.Write ( Str );
}
}
}
// 检查文件类型MIME
// 上传文件类型
// 常见文件的MIME类型
// GIF文件 "image/gif"
// BMP文件 "image/bmp"
// JPG文件 "image/jpeg"
// PNG文件 "image/x-png"
// ICO文件 "image/x-icon"
// zip文件 "application/x-zip-compressed"
// DOC文件 "application/msword"
// 文本文件 "text/plain"
// HTML文件 "text/html"
// 一般文件 "application/octet-stream"
// SWF文件 "application/x-shockwave-flash"
// RAR文件 "application/octet-stream"
// MDB文件 "application/msaccess"
// 所有图片检验例句 "fType.Substring(0,5)"
// 其他文件检验例句 "fType.ToString()"