asp.net图片上传示例

.aspx代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>asp.net图片上传示例</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:Button ID="btnUp" runat="server" Text="上传图片" OnClick="btnUp_Click" />
        
<asp:FileUpload ID="picupload" runat="server" /></div>
    
</form>
</body>
</html>

.cs代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {

    }
    
/// <summary>
    
/// 当没有选择图片时,使用默认图片。为了保存在数据库中。
    
/// </summary>
    
/// <returns></returns>
    private string getimagepath()
    {
        
try
        {
            
return this.picupload.HasFile ? picupload.FileName : "nopic.jpg";
        }
        
catch
        {
            
return "nopic.jpg";
        }
    }
    
protected void submitBt_Click(object sender, EventArgs e)
    {


    }
    
protected void btnUp_Click(object sender, EventArgs e)
    {
        
string savePath = @"images/teachers/";//图片保存路径
        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;
        }
        
string imagepath = ImageName;
        
if (fileName != "nopic.gif")
        {
            picupload.SaveAs(savePath);
        }
        Page.ClientScript.RegisterClientScriptBlock(
this.GetType(), "alert""<script>alert('图片上传成功!')</script>"false);
    }
}

 

posted @ 2009-06-30 09:35  大气象  阅读(827)  评论(2编辑  收藏  举报
http://www.tianqiweiqi.com