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;
}