webconfig 配置
<!--檔案上傳類型-->
<add key="FileType" value=".doc,.xls,.txt,.rar"/>
<add key="PicTureTye" value=".jpg|.gif|.png|.bmp|.psd|.svg|"/>
<!--上傳檔案大小-->
<add key="FileSizeLimit" value="102400"/>
#region 判斷上傳檔案類型
protected bool IsAllowableFileType()
{
//從web.config讀取判斷檔案類型限制
string strFileTypeLimit = ConfigurationManager.AppSettings["FileType"].ToString();
//當前副檔名是否包含在這個字串中
if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUp.FileName).ToLower()) != -1)
{
return true;
}
else
return false;
}
protected bool IsAllowablePictureType()
{
//從web.config讀取判斷圖片類型限制
string strFileTypeLimit = ConfigurationManager.AppSettings["PicTureTye"].ToString();
//當前副檔名是否包含在這個字串中
if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUp.FileName).ToLower()) != -1)
{
return true;
}
else
return false;
}
#endregion
#region 判斷檔案大小限制
private bool IsAllowableFileSize()
{
//從web.config讀取判斷檔案大小的限制
double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]) * 1024;
//判斷檔案是否超出了限制
if (iFileSizeLimit > FileUp.PostedFile.ContentLength)
{
return true;
}
else
{
return false;
}
}
#endregion
protected void btnUpFile_Click(object sender, EventArgs e)
{
//判讀是否有上傳檔案
if (FileUp.PostedFile.ContentLength > 0)
{
if (IsAllowableFileType())
{
if (Directory.Exists(Server.MapPath("~/File")) == false)//判斷檔案夾是否存在,若不存在則建立
{
Directory.CreateDirectory(Server.MapPath("~/File"));
}
else
if (IsAllowableFileSize())
{
//string UploadFilePath = ConfigurationManager.AppSettings["UploadFile"].ToString();
string UploadFilePath = Server.MapPath("File\\");
string fullName = FileUp.PostedFile.FileName;
string newName = DateTime.Now.Ticks.ToString() + fullName.Substring(fullName.LastIndexOf("."));
FileUp.SaveAs(UploadFilePath + newName);
lblFileUrl.Text = fullName.Substring(fullName.LastIndexOf("\\")) + " 上傳成功";
lblSaveFileName.Text = newName;
}
else
MessegeBox.Show(this, "檔案太大了,上傳失敗");
}
else
MessegeBox.Show(this, "檔案類型不正確,上傳失敗");
}
else
{
MessegeBox.Show(this, "上傳檔案為空白,上傳失敗");
}
}
到這裡,檔案已經上傳到一個File檔案夾中了,當然,如果要把路徑儲存到資料庫,你需要另外寫一個儲存路徑到資料庫的方法,在此就不在贅述了。
如果有需要儲存入資料庫的方法,給我留言,我會回複.