我在以前的开发中经常遇到这样的场景:文件上传之后需要显示文件名,但是asp.net自带的fileupload是不能付给上传后的文件名值的。
以前都是做一个label显示的,今天想起来了,写个控件封装一下,直接上代码
控件的代码:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace Fang{ [DefaultProperty("Text")] [ToolboxData("<{0}:FangFileUpload runat=server> ")] public class FangFileUpload : FileUpload { ////// 指示是否上传成功,上传成功后直接反应文件名称和一个删除按钮 /// [ Browsable(false), Description("设置或获取是否上传成功的标记") ] public bool IsUploaded { get { return ViewState["IsUploaded"] == null ? false : (bool)ViewState["IsUploaded"]; } set { ViewState["IsUploaded"] = value; } } ////// 上传成功的文件名啊 /// public string UploadedFileName { get { return ViewState["UploadedFileName"] == null ? null : ViewState["UploadedFileName"].ToString(); } set { ViewState["UploadedFileName"] = value; } } ////// 微软默认在这里加了file属性,去掉 /// /// protected override void AddAttributesToRender(HtmlTextWriter writer) { //没有上传的时候客户端才需要id和name if (!this.IsUploaded) { string uniqueID = this.UniqueID; if (uniqueID != null) { writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID); } string clientID = this.ClientID; if (clientID != null) { writer.AddAttribute(HtmlTextWriterAttribute.Id, clientID); } } } ////// 判断是应该显示div,还是file /// protected override HtmlTextWriterTag TagKey { get { if (IsUploaded) { return HtmlTextWriterTag.P; } else { return HtmlTextWriterTag.Input; } } } ////// 输出div或者file /// /// protected override void Render(HtmlTextWriter writer) { if (!IsUploaded) { writer.AddAttribute(HtmlTextWriterAttribute.Type, "file"); base.Render(writer); } else { base.RenderBeginTag(writer); writer.Write(string.IsNullOrEmpty(UploadedFileName) ? "未命名上传文件" : UploadedFileName); base.RenderEndTag(writer); } } }}
测试代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><%@ Register Assembly="FangFileUpload" Namespace="Fang" TagPrefix="Fang" %>
using System;using System.Collections.Generic;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { } protected void btn_Click(object sender, EventArgs e) { if (FangFileUpload1.HasFile) { FangFileUpload1.SaveAs(Server.MapPath("~/upload/") + FangFileUpload1.FileName); //上传成功 FangFileUpload1.IsUploaded = true; FangFileUpload1.UploadedFileName = FangFileUpload1.FileName; } }}