asp.net上传图片(简单)

时间:2020-12-28 05:32:19

FileUpload:

protected void UploadButton_Click(object sender, EventArgs e)
{
long id = Request.QueryString["id"] == null ? - : Convert.ToInt64(Request.QueryString["id"]);
string pname = id.ToString();
//查找前台中创建的FileUpload1对象并获取路径
FileUpload file=null ;
for (int i = ; i < DataList1.Items.Count; i++)
{
file = (FileUpload)DataList1.Items[i].FindControl("FileUpload1");
}
string uploadName = file.PostedFile.FileName.ToString(); //获取待上传图片的完整路径,包括文件名 string pictureName = "";//上传后的图片名,以当前表的主键为文件名,确保文件名没有重复 if (uploadName != "")
{
int idx = uploadName.LastIndexOf(".");
string suffix = uploadName.Substring(idx);//获得上传的图片的后缀名
suffix = suffix.ToLower(); if (suffix == ".jpg" || suffix == ".gif" || suffix == ".bmp" || suffix == ".png")
{
pictureName = pname + suffix; // 注:也可以当前时间为文件名
// pictureName = DateTime.Now.Ticks.ToString() + suffix;
}
else
{
Response.Write("<script>alert('图片格式不正确!')</script>");
Response.End();
}
}
try
{
if (uploadName != "")
{
string path = Server.MapPath("~/Photo/");
file.PostedFile.SaveAs(path + pictureName);
Response.Write("<script>alert('图片上传成功!')</script>");
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}