using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile.FileName == string.Empty)
{
Response.Write("<script>alert('请选择要上传的文件!');</script>");
}
else
{
//获取要上传的文件的信息
string filepath = FileUpload1.PostedFile.FileName;//文件路径
string oldfilename = filepath.Substring(filepath.LastIndexOf("\\")+1);//文件名
string FileExtension = Path.GetExtension(oldfilename); //文件的扩展名
int filelength = (int)oldfilename.Length;//文件名长度
//随机生成文件名
Random Rnd = new Random();
int strRnd = Rnd.Next(1, 99);
string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + strRnd.ToString() + FileExtension.ToLower();
//将文件上传到以当前日期命名的文件夹中
string UpLoadName = DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString()+"-"+DateTime.Now.Day.ToString();
bool FileUploadPathExists = File.Exists(Server.MapPath("UpLoad"+"\\"+UpLoadName));
//指定文件夹不存在,如果不存在就创建该文件夹
if (!FileUploadPathExists)
{
Directory.CreateDirectory(Server.MapPath("UpLoad"+"\\"+UpLoadName));
}
//保存上传的文件
string savapath = Server.MapPath("UpLoad" + "\\" + UpLoadName);//保存路径
string savapath1 = "UpLoad" + "\\" + UpLoadName +"\\"+ newfilename;//保存路径
FileUpload1.PostedFile.SaveAs(savapath + "\\" + newfilename);
//连接数据库字符串
string connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Web_Test\WebSite4\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string cmdtext = "insert into T_UpFile(FileName,FileLength,FileType,FilePath) values('" + newfilename + "','" + filelength + "','" + FileExtension + "','"+savapath1+"')";
SqlCommand cmd = new SqlCommand(cmdtext, conn);
try
{
cmd.ExecuteNonQuery();
System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
strMsg.Append("<font color=green>文件被成功添加到数据库中,详细信息如下所示:<br>");
strMsg.Append("上传的文件的类型为:" + this.FileUpload1.PostedFile.ContentType.ToString() + "<br>");
strMsg.Append("客户端文件的地址为:" + filepath + "<br>");
strMsg.Append("上传文件的文件名为:" + newfilename + "<br>");
strMsg.Append("文件上传到服务器的路径为:" + savapath + "<br>");
strMsg.Append("上传文件的扩展名为:" + FileExtension + "<br>");
strMsg.Append("上传文件的大小为:" + FileUpload1.PostedFile.ContentLength + "个字节</font>");
this.Label1.Text = strMsg.ToString();
}
catch (Exception error)
{
Response.Write(error.ToString());
}
finally
{
conn.Close();
}
}
}
}
//数据库设计
create T_UpFile
(
FileID int identity(100000,1) primary key,
FileName varchar(50),
FileLength int ,
FileType varchar(20),
FilePath varchar(MAX),
)