asp.net上传图片

时间:2021-12-14 01:38:34

<%@ control language="C#" autoeventwireup="true" inherits="Admin_PicUpload, App_Web_mboefw14" %>
&nbsp;<asp:Image ID="EP_Image" runat="server" Height="160px" ImageUrl='<%# Bind("EP_Pic") %>'
     Width="314px" />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" />


自定义用户控件文件 PicUpload.ascx.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 Admin_PicUpload : System.Web.UI.UserControl
{
     protected void Page_Load(object sender, EventArgs e)
     {

     }
     protected void Button1_Click(object sender, EventArgs e)
     {
         bool fileOK = false;
         //获取根文件绝对路径
         string path = Server.MapPath("~/UpLoad/");
        //如上传了文件,就判断文件格式
         FileUpload FU = FileUpload1;
         if (FU.HasFile)
         {
             string fileExtension = System.IO.Path.GetExtension(FU.FileName).ToLower();
             string[] allowedExtensions ={ ".gif", ".jpg", ".png", ".bmp", };
             for (int i = 0; i < allowedExtensions.Length; i++)
             {
                 if (fileExtension == allowedExtensions[i])
                 {
                     fileOK = true;
                 }
             }
         }
         //调用saveas方法,实现上传文件
         if (fileOK)
         {
             try
             {
                 FileUpload1.SaveAs(path + System.DateTime.Now.ToString("yyyyMMddhhmmss")+FU.FileName);
                 EP_Image.ImageUrl = "../Upload/" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + FU.FileName;
                 Button1.Text = "上传成功";
             }
             finally
             {
             }
         }
         else
         {
             Button1.Text = "上传失败,格式不允许";
         }
     }
}