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";
        }
    }
posted @ 2009-09-10 16:47  大气象  阅读(616)  评论(1编辑  收藏  举报
http://www.tianqiweiqi.com