asp.net实现图片上传
protected void btnAdd_Click(object sender, EventArgs e)
{
if (txtName.Text == "")
{
Tools.Alert("填写图片名称!", this);
return;
}
string savePath = @"../images/picnews/";//图片保存路径
string fileName = Server.HtmlEncode(this.getimagepath());
string extension = System.IO.Path.GetExtension(fileName);//取得扩展名
string ImageName = "";
if (fileName != "nopic.gif")
{
if ((extension == ".jpg") | (extension == ".gif"))
{
ImageName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + extension;
savePath += ImageName;
savePath = Server.MapPath(savePath);
}
else
{
Response.Write("<script>alert('文件上传格式错误');history.back(1);</script>");
Response.End();
}
}
else
{
ImageName = fileName;
}
if (fileName != "nopic.gif")
{
picupload.SaveAs(savePath);//这里是asp:FileUpload控件
}
AProduct.AddProduct(txtName.Text, FreeTextBox1.Text, ImageName, Convert.ToInt32(ddlType.SelectedValue), FreeTextBox2.Text);
Tools.Alert("添加成功!", this);
}
/// <summary>
/// 当没有选择图片时,使用默认图片。为了保存在数据库中。
/// </summary>
/// <returns></returns>
private string getimagepath()
{
try
{
return this.picupload.HasFile ? picupload.FileName : "nopic.gif";
}
catch
{
return "nopic.gif";
}
}
{
if (txtName.Text == "")
{
Tools.Alert("填写图片名称!", this);
return;
}
string savePath = @"../images/picnews/";//图片保存路径
string fileName = Server.HtmlEncode(this.getimagepath());
string extension = System.IO.Path.GetExtension(fileName);//取得扩展名
string ImageName = "";
if (fileName != "nopic.gif")
{
if ((extension == ".jpg") | (extension == ".gif"))
{
ImageName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + extension;
savePath += ImageName;
savePath = Server.MapPath(savePath);
}
else
{
Response.Write("<script>alert('文件上传格式错误');history.back(1);</script>");
Response.End();
}
}
else
{
ImageName = fileName;
}
if (fileName != "nopic.gif")
{
picupload.SaveAs(savePath);//这里是asp:FileUpload控件
}
AProduct.AddProduct(txtName.Text, FreeTextBox1.Text, ImageName, Convert.ToInt32(ddlType.SelectedValue), FreeTextBox2.Text);
Tools.Alert("添加成功!", this);
}
/// <summary>
/// 当没有选择图片时,使用默认图片。为了保存在数据库中。
/// </summary>
/// <returns></returns>
private string getimagepath()
{
try
{
return this.picupload.HasFile ? picupload.FileName : "nopic.gif";
}
catch
{
return "nopic.gif";
}
}
我这个博客废弃不用了,今天想寻找外链的时候,突然想到这个博客权重很高。
有需要免费外链的,留言即可,我准备把这个博客变成免费的友情链接站点。