您的位置:首页 > 其它

FileUpload 控件 上传图片 到服务器

2010-12-05 17:17 169 查看
这个是关于如何利用FileUpload 控件把图片上传到服务器的案例,

/// <summary>

/// 上传图片

/// </summary>

protected void btnUpImage_Click(object sender, EventArgs e)

{

string FileName, FileLastName;

try

{

FileName = FileUpload1.FileName;//获取文件名

FileLastName = FileName.Substring(FileName.LastIndexOf(".") + 1);//得到文件的扩展名

// ShowSellerName = System.Web.HttpContext.Current.Session["SellerName"].ToString().Trim();//把会话中的名称保存起来

Random R = new Random();//创建产生随机数

int val = 10 + R.Next(99);//产生随机数为99以内任意

string sc = val.ToString();//产生随机数

string FileTime = DateTime.Now.ToString("yyyyMMddHHmmss") + sc;//得到系统时间(格式化)并加上随机数以便生成上传图片名称

string UploadFileName = FileTime + "." + FileLastName;//产生上传图片的名称

//string UD = ShowSellerName;//创建用户的文件夹的名字

string Parth = System.Web.HttpContext.Current.Server.MapPath("upload").ToString() + "//";//创建虚拟路径

if (!Directory.Exists(Parth)) //如果文件夹不存在则创建

{

//捕获异常

try

{

Directory.CreateDirectory(Parth);//创建文件夹与用户名同名

//判断FileUpload组件是否存在内容

if (FileUpload1.HasFile)

{

FileUpload1.PostedFile.SaveAs(Parth + UploadFileName);//上传图片(自定义)

string User_ProductsImageUrl = "/Manage/Equipment/upload/" + UploadFileName;//得到服务端图片的虚拟路径

System.Web.HttpContext.Current.Session["GoodsImageUrl"] = User_ProductsImageUrl;//保存获得的图片虚拟路径进行跨页面间的传递

}

else

{

//显示出错信息

System.Web.HttpContext.Current.Response.Redirect("~/Tips/Error.aspx");

}

}

catch (IOException)

{

//显示出错信息

System.Web.HttpContext.Current.Response.Redirect("~/Tips/Error.aspx");

}

}

else

{

//判断FileUpload组件是否存在内容

if (FileUpload1.HasFile)

{

FileUpload1.PostedFile.SaveAs(Parth + UploadFileName);//上传图片(自定义)

string User_ProductsImageUrl = "/Manage/Equipment/upload/" + UploadFileName;//得到服务端图片的虚拟路径

labUrl.Text = User_ProductsImageUrl;

System.Web.HttpContext.Current.Session["ImageUrl"] = User_ProductsImageUrl;//保存获得的图片虚拟路径进行跨页面间的传递

lb_info.Text = "恭喜你图片上传成功!";

}

}

}

catch (Exception error)

{

this.lb_info.Text = "上传发生错误!原因:" + error.ToString();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐