实现文件上传

Upload.aspx

None.gif < form  id ="PostUp"  method ="post"  encType ="multipart/form-data"  runat ="server" >
None.gif            文件路径: 
&nbsp;&nbsp;   < input  id ="PostUpFile"  type ="file"  size ="30"  name ="PostUpFile"  runat ="server" >
None.gif            
< asp:button  id ="btn_PostUp"  runat ="server"  Text ="上传"  Height ="20px" ></ asp:button >
None.gif        
</ form >


Upload.aspx.cs

None.gif using  System;
None.gif
using  System.Collections;
None.gif
using  System.ComponentModel;
None.gif
using  System.Data;
None.gif
using  System.Data.SqlClient;
None.gif
using  System.Drawing;
None.gif
using  System.Drawing.Imaging;
None.gif
using  System.Web;
None.gif
using  System.Web.SessionState;
None.gif
using  System.Web.UI;
None.gif
using  System.Web.UI.WebControls;
None.gif
using  System.Web.UI.HtmlControls;
None.gif
using  System.Configuration;
None.gif
using  System.IO;
None.gif
using  System.Text;
None.gif
None.gif
namespace  Sample.Upload_Sample
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Upload 的摘要说明。
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class Upload : System.Web.UI.Page
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
protected System.Web.UI.HtmlControls.HtmlInputFile PostUpFile;
InBlock.gif        
protected System.Web.UI.WebControls.Button btn_PostUp;
InBlock.gif        
long FileMaxSize = Convert.ToInt32(ConfigurationSettings.AppSettings["FileMaxSize"]);
InBlock.gif        SqlConnection Conn;
InBlock.gif
InBlock.gif    
InBlock.gif        
private void Page_Load(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// 在此处放置用户代码以初始化页面
InBlock.gif
            
ExpandedSubBlockEnd.gif        }

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
InBlock.gif        
override protected void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//
InBlock.gif            
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
InBlock.gif            
//
InBlock.gif
            InitializeComponent();
InBlock.gif            
base.OnInit(e);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
InBlock.gif        
/// 此方法的内容。
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{    
InBlock.gif            
this.btn_PostUp.Click += new System.EventHandler(this.btn_PostUp_Click);
InBlock.gif            
this.Load += new System.EventHandler(this.Page_Load);
InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
InBlock.gif        
private void btn_PostUp_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string fName,FileName,SaveName,Extension,PrewImagName,PrewImagNamePath;
InBlock.gif            
int CheckFileType;
InBlock.gif            
int FontSize;
InBlock.gif            
long FileSize;
InBlock.gif            FontSize 
= 20//字符水印字体大小
InBlock.gif
            string addText = "字符水印"//字符水印内容
InBlock.gif
            
InBlock.gif            
if(PostUpFile.PostedFile.FileName.Trim()!="")  //上传文件名非空
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    CreateDirectory();
InBlock.gif                    fName 
= PostUpFile.PostedFile.FileName.ToString();
InBlock.gif                    Extension 
= Path.GetExtension(PostUpFile.PostedFile.FileName).ToLower();
InBlock.gif                    FileSize 
= PostUpFile.PostedFile.ContentLength;  
InBlock.gif                    
InBlock.gif                    
InBlock.gif                    
//判断文件类型:0=其它,1=图片,2=FLASH,3=音乐,4=电影
InBlock.gif
                    switch (Extension)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
case ".gif":CheckFileType = 1;break;
InBlock.gif                        
case ".jpg":CheckFileType = 1;break;
InBlock.gif                        
case ".jpeg":CheckFileType = 1;break;
InBlock.gif                        
case ".png":CheckFileType = 1;break;
InBlock.gif                        
case ".bmp":CheckFileType = 1;break;
InBlock.gif                        
case ".swf":CheckFileType = 2;break;
InBlock.gif                        
case ".swi":CheckFileType = 2;break;
InBlock.gif                        
case ".mid":CheckFileType = 3;break;
InBlock.gif                        
case ".wav":CheckFileType = 3;break;
InBlock.gif                        
case ".mp3":CheckFileType = 3;break;
InBlock.gif                        
case ".avi":CheckFileType = 4;break;
InBlock.gif                        
case ".ra":CheckFileType = 4;break;
InBlock.gif                        
case ".rm":CheckFileType = 4;break;
InBlock.gif                        
case ".mpg":CheckFileType = 4;break;
InBlock.gif                        
case ".mpeg":CheckFileType = 4;break;
InBlock.gif                        
case ".asf":CheckFileType = 4;break;
InBlock.gif                        
case ".wov":CheckFileType = 4;break;
InBlock.gif                        
default:CheckFileType = 0;break;
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
InBlock.gif                    
//检查文件类型及大小
InBlock.gif
                        if(Extension == ".asp" || Extension == ".aspx" || Extension == ".php" || Extension == ".jsp" || Extension == ".asa" )
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            ShowMsg(
"上传文件类别超出限定范围!");
InBlock.gif                            
InBlock.gif                            
return;
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
if(FileSize > FileMaxSize)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            ShowMsg(
"上传文件大小超出范围!");
InBlock.gif                            
return;
ExpandedSubBlockEnd.gif                        }

InBlock.gif                    
InBlock.gif                    FileName 
= CreateFileName() + Extension;
InBlock.gif                    SaveName 
= "UploadFiles/" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "/" + FileName;
InBlock.gif                    
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        PostUpFile.PostedFile.SaveAs(CreateDirectory() 
+ "\\" + FileName);
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
catch(IOException)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        ShowMsg(
"上传失败");
InBlock.gif                        
return;
ExpandedSubBlockEnd.gif                    }

InBlock.gif
InBlock.gif                        
//如果文件是"bmp,jpg,jpeg,gif"则生成预览图并加上水印
InBlock.gif
                    
InBlock.gif                        
if (Extension == ".gif" || Extension == ".jpg" || Extension == ".jpeg" || Extension == ".bmp" || Extension == ".png")
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
//1.加文字水印,注意,这里的代码和以下加图片水印的代码不能共存    
InBlock.gif
                        
InBlock.gif                            System.Drawing.Image image 
= System.Drawing.Image.FromFile(CreateDirectory() + "\\" + FileName);
InBlock.gif                            Graphics g 
= Graphics.FromImage(image);
InBlock.gif                            g.DrawImage(image, 
00, image.Width, image.Height);
InBlock.gif                            Font f 
= new Font("迷你简粗倩", FontSize, System.Drawing.FontStyle.Bold);
InBlock.gif                            Brush b 
= new SolidBrush(Color.White);
InBlock.gif                            g.DrawString(addText, f, b, 
55);
InBlock.gif                            g.Dispose();
InBlock.gif                        
InBlock.gif
InBlock.gif                            
//2.加图片水印
ExpandedSubBlockStart.gifContractedSubBlock.gif
                            /**//*
InBlock.gif                            System.Drawing.Image image = System.Drawing.Image.FromFile(CreateDirectory() + "\\" + FileName);
InBlock.gif                            System.Drawing.Image copyImage = System.Drawing.Image.FromFile( Server.MapPath("..//Images//") + "CopyRight.gif");
InBlock.gif                            Graphics g = Graphics.FromImage(image);
InBlock.gif                            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);
InBlock.gif                            g.Dispose();
ExpandedSubBlockEnd.gif                            
*/

InBlock.gif
InBlock.gif
InBlock.gif                            
//预览图地址
InBlock.gif
                            PrewImagName = "PrewImages/" + "Prew_" + FileName;
InBlock.gif                            PrewImagNamePath 
= Server.MapPath("PrewImages\\").ToString() + "Prew_" + FileName;
InBlock.gif                            image.Save(PrewImagNamePath);
InBlock.gif                            image.Dispose();
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            PrewImagName 
= "none";
ExpandedSubBlockEnd.gif                        }

InBlock.gif
InBlock.gif                        
//保存文件信息到数据库
InBlock.gif
                        string strSQL = "Insert into UploadFiles (f_joindate,f_filename,f_savename,f_prewimg,f_type,f_extname,f_size) Values("
InBlock.gif                            
+ "'" + DateTime.Now.ToString() + "',"
InBlock.gif                            
+ "'" + FileName + "',"
InBlock.gif                            
+ "'" + SaveName + "',"
InBlock.gif                            
+ "'" + PrewImagName + "',"
InBlock.gif                            
+ CheckFileType + ","
InBlock.gif                            
+ "'" + Extension.Replace(".","").ToString().Trim() + "',"
InBlock.gif                            
+ FileSize + ")";
InBlock.gif
InBlock.gif                        Conn 
= new SqlConnection(var.StrConn);        
InBlock.gif                        SqlCommand myCmd 
= new SqlCommand(strSQL,Conn);
InBlock.gif                        Conn.Open();
InBlock.gif                        myCmd.ExecuteNonQuery();
InBlock.gif                        myCmd.Dispose();
InBlock.gif                        Conn.Close();
InBlock.gif                        Response.Write (
"<script language='javascript'>alert('上传文件成功!');location='Default.aspx';</script>");
InBlock.gif                    
InBlock.gif                    
ExpandedSubBlockEnd.gif                }

InBlock.gif                
catch(Exception er)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    ShowMsg(er.Message);
ExpandedSubBlockEnd.gif                }

InBlock.gif                
InBlock.gif                
ExpandedSubBlockEnd.gif            }

InBlock.gif
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
//检查目录存在并添加新目录
InBlock.gif
        private string CreateDirectory()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string Path,Dic;
InBlock.gif            Dic 
= Server.MapPath("UploadFiles\\").ToString() + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString();
InBlock.gif            Path 
= @Dic;
InBlock.gif             
InBlock.gif            
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
// 检查目录是否已经创建.
InBlock.gif
                if (Directory.Exists(Path)) 
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return Dic;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
// 尝试创建目录
InBlock.gif
                DirectoryInfo di = Directory.CreateDirectory(Path);
InBlock.gif                
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
catch (Exception e) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                ShowMsg(
"建立日期文件夹出错!");
ExpandedSubBlockEnd.gif            }
 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
finally dot.gif{}
InBlock.gif            
InBlock.gif            
return Dic;
InBlock.gif            
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
//创建文件名
InBlock.gif
        private string CreateFileName()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Random rnd 
= new Random();
InBlock.gif            StringBuilder sb 
= new StringBuilder();
InBlock.gif            
int i;
InBlock.gif            
for (i=0;i<=5;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                sb.Append(rnd.Next(
0,9).ToString());            
ExpandedSubBlockEnd.gif            }

InBlock.gif            
string EXT = sb.ToString();
InBlock.gif            
string FileName = "Yandd_" + DateTime.Now.Year.ToString()
InBlock.gif                
+ DateTime.Now.Month.ToString()
InBlock.gif                
+ DateTime.Now.Day.ToString()
InBlock.gif                
+ DateTime.Now.Hour.ToString()
InBlock.gif                
+ DateTime.Now.Minute.ToString()
InBlock.gif                
+ DateTime.Now.Second.ToString()
InBlock.gif                
+ EXT;
InBlock.gif            
return FileName;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
//发现错误Alert
InBlock.gif
        private void ShowMsg(string err)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string Str;
InBlock.gif            Str
="<script language='javascript'>";
InBlock.gif            Str
+=" alert('" +err + "')";
InBlock.gif            Str
+="</script>";
InBlock.gif            Response.Write ( Str );
InBlock.gif                
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif                    
// 检查文件类型MIME
None.gif                    
// 上传文件类型
None.gif                    
// 常见文件的MIME类型
None.gif                    
// GIF文件  "image/gif"
None.gif                    
// BMP文件 "image/bmp"
None.gif                    
// JPG文件 "image/jpeg"
None.gif                    
// PNG文件 "image/x-png"
None.gif                    
// ICO文件 "image/x-icon"
None.gif                    
// zip文件 "application/x-zip-compressed"
None.gif                    
// DOC文件 "application/msword"
None.gif                    
// 文本文件 "text/plain"
None.gif                    
// HTML文件 "text/html"
None.gif                    
// 一般文件 "application/octet-stream"
None.gif                    
// SWF文件 "application/x-shockwave-flash"
None.gif                    
// RAR文件 "application/octet-stream"
None.gif                    
// MDB文件 "application/msaccess"
None.gif                    
// 所有图片检验例句 "fType.Substring(0,5)"
None.gif                    
// 其他文件检验例句 "fType.ToString()"

转载于:https://www.cnblogs.com/violet_xml/archive/2010/05/10/1731718.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值