1、.aspx代碼
<table>
<tr>
<td class="tdleft" style="width: 125px;">
頭像:
</td>
<td class="tdright">
<asp:Label ID="lbPicName" runat="server"> </asp:Label>
</td>
</tr>
<tr>
<td class="tdleft" style="width: 125px;">
頭像上傳:
</td>
<td class="tdright">
<input id="fileImages" type="file" name="fileImage" runat="server" size="35" tabindex="2"
style="height: 25px;" />
<asp:Button ID="UploadImage" Text="上傳" runat="server" OnClick="UploadImage_Click"
Width="52px" />
</td>
</tr>
</table>
2.cs代碼
private string ProPicPath = System.Configuration.ConfigurationManager.AppSettings["PicPath"].ToString(); //webconfig配置上傳到服務器地址 物理
public string ProPicUrl = System.Configuration.ConfigurationManager.AppSettings["PicUrl"].ToString();//取圖片的路徑 虛
#region 上傳圖片
/// <summary>
/// 上傳圖片事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void UploadImage_Click(object sender, EventArgs e)
{
try
{
#region 圖片上傳
if (fileImages.PostedFile.FileName == "")
{
RaiseErrorMessage("請選擇要上傳的圖片");
return;
}
if (fileImages.PostedFile.ContentLength < 1)
{
RaiseErrorMessage("您上傳的文件大小爲 0 KB");
return;
}
// RaiseErrorMessage(fileImages.PostedFile.ContentLength.ToString());
string filePath = fileImages.PostedFile.FileName;
//string filename = filePath.Substring(filePath.LastIndexOf("\\") + 1);
//擴展名
string strFileFullName = fileImages.PostedFile.FileName;
string strExcCaps = System.IO.Path.GetExtension(strFileFullName).ToLower();
DateTime datetime = DateTime.Now;
string filename = "img" + datetime.Year.ToString() + datetime.Month.ToString() + datetime.Day.ToString() + datetime.Hour.ToString() + datetime.Minute.ToString() + datetime.Second.ToString() + datetime.Millisecond.ToString() + strExcCaps;
if (strExcCaps != ".jpg" && strExcCaps != ".gif" && strExcCaps != ".jpeg")
{
RaiseErrorMessage("您只能上傳 *.gif,*.jpg,*.jpeg 格式的圖片");
return;
}
string oldFileName = UpLoadImgServer(fileImages, ProPicPath, filename);
lbPicName.Text = filename;
#endregion
}
catch (Exception error)
{
throw (error);
}
}
#endregion
#region 彈出客戶端提示
/// <summary>
/// 彈出客戶端提示
/// </summary>
/// <param name="sMessage"></param>
private void RaiseErrorMessage(string sMessage)
{
this.ClientScript.RegisterClientScriptBlock(typeof(string), "", "<script>alert('" + sMessage.Replace("'", "\"") + "');</script>");
}
#endregion
//上傳圖片的方法
public string UpLoadImgServer(HtmlInputFile UpFile, string strpath, string names)
{
try
{
if (Directory.Exists(strpath) == false)
Directory.CreateDirectory(strpath);
}
catch { }
System.Web.HttpPostedFile postfile = UpFile.PostedFile;
string strname = postfile.FileName;
string strnewpath = strpath + names;
postfile.SaveAs(strnewpath);
return strnewpath;
}