Aspx代码
<head runat="server">
<title>
</title>
</head>
<body>
<form id="form1" runat="server">
<br />
<br />
<br />
<table align="center" border="1" cellpadding="0" cellspacing="0" bordercolor="#3399ff" style="width: 749px">
<tr>
<td align="center" style="width:267px" >
<input type="file" runat="server" id="fileuploadid" style="width: 439px" />
</td>
<td align="right" style="width:150px"><asp:Button runat="server" ID="btupload" OnClick="BtUpLoad" Text="上传" />
</td>
</tr>
</table>
</form>
</body>
</html>
aspx.cs代码
using System;
using System.Data;
using System.Data.SqlClient;
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.IO;
public partial class _Default : System.Web.UI.Page
{
protected string DefaultTitle = ConfigurationSettings.AppSettings["SystemName"].ToString(); //获取系统名称
protected string strConn = ConfigurationSettings.AppSettings["strSqlConn"].ToString(); //获取数据库连接字条串
protected string UploadFileTypes = ConfigurationSettings.AppSettings["UploadFileType"].ToString(); //获取允许上传的格式
protected string UploadSavePath = ConfigurationSettings.AppSettings["UploadSavePath"].ToString(); //获取附件保存根目录,如upfiles/
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 上传附件并添加上传附件记录到数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void BtUpLoad(object sender, EventArgs e)
{
string filePath; //文件路径
string fileName; //附件名称
int fileSize; //附件大小
string fileType; //附件格式
string sAbsoluteSavePath; //服务器端附件保存根目录
string sFileSaveName; //附件保存在服务器上的名称
int tt;
string savePath;
if (fileuploadid.PostedFile.FileName != "")
{
savePath = DateTime.Now.ToString("yyyyMM")+"/"; //指定上传附件保存的目录,根据年月生成 如200804/
Exception excp = InitUploadSaveDirectory(savePath);
//如果返回异常则退出程序
if (excp != null)
{
Response.Write(excp.ToString());
return;
}
filePath = fileuploadid.PostedFile.FileName;
fileName = Path.GetFileName(filePath); //原始附件名称
fileSize = fileuploadid.PostedFile.ContentLength; //附件大小
tt = fileName.LastIndexOf(".");
fileType = fileName.Substring(tt).ToLower(); //附件格式,小写
//获取服务端附件保存根目录,如D:/上传/upfiles/200804/
sAbsoluteSavePath = Path.Combine(Request.MapPath(UploadSavePath), savePath);
//指定附件保存在服务器上的名称(根本上传时间生成,重名处理)
sFileSaveName = DateTime.Now.ToString("MMdd") + DateTime.Now.ToString("hhmmss") + fileType;
if (fileSize > 0 && fileType.Length > 0 && ("|" + UploadFileTypes + "|").IndexOf("|" + fileType + "|") > -1)
{
try
{
string sqlInsert;
fileuploadid.PostedFile.SaveAs(Path.Combine(sAbsoluteSavePath, sFileSaveName));
SqlConnection sqlcon = new SqlConnection(strConn);
sqlInsert = "insert into web_AttachmentInfo(FileName,OrigialName,SavePath,FileSize,Uptime) values('" + sFileSaveName + "','" + fileName + "','" + sAbsoluteSavePath + "','" + fileSize + "','" + DateTime.Now.ToString("yyyy - MM - dd") + "')";
SqlCommand sqlcom = new SqlCommand(sqlInsert,sqlcon);
sqlcon.Open();
sqlcom.ExecuteNonQuery();
Response.Write("<script>alert('上传成功!');</script>");
}
catch (Exception ex)
{
Response.Write("错误:" +ex.Message);
}
}
}
else
{
Response.Write("<script>alert('靠,先选个附件啊!');</script>");
}
}
/// <summary>
/// 初始化上传目录
/// </summary>
/// <param name="savePath">附件保存目录的格式或者路径</param>
/// <returns>如果创建保存路径失败将返回异常</returns>
private Exception InitUploadSaveDirectory(string savePath)
{
if (UploadSavePath == null)
{
throw new ArgumentNullException("UploadSavePath");
}
//获取服务端附件保存根目录,如D:/上传/upfiles/200804/
string sAbspath = Request.MapPath(UploadSavePath);
//如果路径不存在就试图创建根目录
if (!Directory.Exists(sAbspath) )
{
Directory.CreateDirectory(sAbspath);
}
sAbspath = Path.Combine(sAbspath,savePath);
//如果保存附件目录不存在就创建该保存目录
if(!Directory .Exists(sAbspath))
{
Directory.CreateDirectory(sAbspath);
}
return null;
}
}
web.config代码
增加几个节点
<appSettings>
<!--定义附件保存的根目录-->
<add key="UploadSavePath" value="UpFiles/"/>
<!--定义允许上传的文件后缀-->
<add key="UploadFileType" value=".gif|.jpg|.jpe|.jpeg|.png|.bmp|.zip|.rar|.ppt|.doc|.xls|.mdb|.ppt|.txt|.pdf|.mp3|.wma"/>
<!--首页名称-->
<add key="SystemName" value="上传文件"/>
<!--定义数据库连接语句-->
<add key="strSqlConn" value="server=11AA7FAB9CBB43E;database=AttachmentInfo;User id=sa;password=sa"/>
</appSettings>
5759





