使用Web控件和集成验证的自定义文件上载

分享于 

13分钟阅读

Web开发

  繁體 雙語

介绍

我已经编写了这篇文章来演示使用web控件。

当我们只希望在单击 。aspx页面上的按钮时触发自定义验证程序,本文将显示的是如何创建简单的文件上载控件,该控件:

  • 仅接受 。gif,。jpg,png,bmp bmp bmp bmp bmp bmp。
  • 允许用户声明是否需要该图像。

所涉及的页面

下面是我们将在其中实现控件的页面( 使用代码文件):

  • Default.aspx
  • Default.aspx.cs

以下是网页控制页面名称:

  • CustomControl.ascx
  • CustomControl.ascx.cs

Web控件的任务( customcontrol。ascx )

对于web控件,我们需要执行以下操作:

  • 添加文件上传
  • 添加自定义验证程序
  • 将某些内容分配给验证程序事件的自定义 ServerValidate

下面是代码:

<%@ControlLanguage="C#"AutoEventWireup="true"CodeFile="CustomControl.ascx.cs"Inherits="WebUserControl"%><asp:FileUploadID="FilUpl"runat="server"/><br/><asp:CustomValidatorID="ErrorMsg"runat="server"ErrorMessage="CustomValidator"OnServerValidate="ErrorMsg_ServerValidate"></asp:CustomValidator><br/>

Web控件代码文件的任务( customcontrol。ascx。cs )

对于Web控件的代码文件,我们需要:

  • 定义所有 private 变量。
  • 定义所有的获取/设置,我们将用来设置标记参数并检索其他参数。
  • 定义我们为自定义验证程序分配的ServerValidate 函数。
  • 定义一个函数以获取要上载的文件的文件扩展名。

下面是代码:

publicpartialclass CustomControl : System.Web.UI.UserControl
{
 //Has the user browsed for a file?privatebool pGotFile;
 //The file extension of the Posted Fileprivatestring pFileExt;
 //The File itselfprivate HttpPostedFile pFilePost;
 //Is the user required to upload an image?privatebool pRequired;
 //The validation group that the Custom Validator belongs to on the pageprivatestring pVgroup;
 //Extensions you allow to be uploadedprivate string[] pFileTypeRange;
 //Boolean indicator to check if file extension is allowedprivatebool Ind = false;
 /* * Get and Sets for the 上面 private variables.
 * */publicbool GotFile
 {
 get { return pGotFile; }
 }
 publicstring FileExt
 {
 get { return pFileExt; }
 }
 public HttpPostedFile FilePost
 {
 get { return pFilePost; }
 }
 publicbool Required
 {
 set { pRequired = value; }
 }
 publicstring Vgroup
 {
 set { pVgroup = value; }
 }
 publicstring FileTypeRange
 {
 set { pFileTypeRange = value.ToString().Split(','); }
 }
 protectedvoid Page_Load(object sender, EventArgs e)
 {
 //here we assign the validation group to the Custom Validator, //which I have inefficiently named ErrorMsg ErrorMsg.ValidationGroup = pVgroup;
 }
 protectedvoid ErrorMsg_ServerValidate(object source, 
 ServerValidateEventArgs args)
 {
 if (FilUpl.HasFile)
 {
 pGotFile = true;
 pFileExt = GetExtension(FilUpl.PostedFile.FileName);
 pFilePost = FilUpl.PostedFile;
 foreach (string str in pFileTypeRange)
 {
 if (str == pFileExt)
 {
 Ind = true;
 }
 }
 if (!Ind)
 {
 args.IsValid = false;
 ErrorMsg.Text = "The file format you" + 
 "specified is not supported";
 //Stop the functionreturn;
 }
 }
 else {
 //So if we get here the user has not browsed for a file pGotFile = false;
 //If you have stated that the user has to browse for a file.//then we must stop now and inform the user of such.if (pRequired)
 {
 args.IsValid = false;
 ErrorMsg.Text = "You must upload something";
 }
 }
 }
 ///<summary>/// This returns the file extension. It does not contain the preceding full stop/// so it would return jpg and NOT. jpg. Please adjust your coding accordingly.///</summary>///<paramname="FileName">string</param>///<returns>string: the file extension e.g. jpg</returns>privatestring GetExtension(string FileName)
 {
 string[] split = FileName.Split('.');
 string Extension = split[split.Length - 1];
 return Extension;
 }
}

测试页的任务( Default.aspx )

  • 在页面最顶端添加标记行,它注册了我们将使用的自定义标记:
  • <%@RegisterTagPrefix="CC1"TagName="IUpload"Src="CustomControl.ascx"%>
  • 添加标签本身以及下面的按钮,我们将使用它来触发文件上传。
  • <CC1:IUploadID="MyUpload1"runat="server"Required="false"Vgroup="Val1"FileTypeRange="jpg,gif,png,bmp"/><asp:ButtonID="Button1"runat="server"Text="Upload Image"CausesValidation="true"ValidationGroup="Val1"OnClick="Button1_Click"/>

页文件的测试代码的任务( 默认。aspx。cs )

  • 添加按钮的事件。
  • 在这里事件中,检查页面是否有效。 检查是否有文件,如果有,请上传。

下面是代码:

publicpartialclass _Default : System.Web.UI.Page 
{
 protectedvoid Page_Load(object sender, EventArgs e)
 {
 }
 protectedvoid Button1_Click(object sender, EventArgs e)
 {
 //First We Check if the page is valid or if we need to flag up an error messageif (Page.IsValid)
 {
 //Second we need to check if the user has browsed for a fileif (MyUpload1.GotFile)
 {
 //We can safely upload the file here because it has passed all validation.//Remeber to add the fullstop before//the FileExt variable as it comes without. MyUpload1.FilePost.SaveAs(Server.MapPath("images/MyFile." + 
 MyUpload1.FileExt));
 }
 }
 }
}

请注意

我使用 ASP.NET 版本 2.0开发了这个版本,还使用了 Visual。

更新

从 11 2006年08月 更新效果

我将给这个加上一些额外的东西。 比如对于文件类型范围,指定x - jpg,png,gif,bmp,然后你可能还要检查图像的宽度是否符合你在标签中设置的最小要求。 它将检查大小,而不用将它保存到磁盘,使用 InputStream

这里的是如何在不将文件保存到磁盘的情况下实现检查:

System.Drawing.Image CheckSize = 
 System.Drawing.Image.FromStream(FilUpl.PostedFile.InputStream);if (CheckSize.PhysicalDimension.Width < minWidth)
{
 //Conditional actions here}

这里是代码,但这次包含了图像大小检查。 如果它不满足所要求的最小宽度,它将输出: "你的图像不符合"+ MinWidth +"px"等等 所要求的最小尺寸要求。

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;publicpartialclass CustomControl : System.Web.UI.UserControl
{
 //Has the user browsed for a file?privatebool pGotFile;
 //The file extension of the Posted Fileprivatestring pFileExt;
 //The File itselfprivate HttpPostedFile pFilePost;
 //Is the user required to upload an image?privatebool pRequired;
 //The validation group that the Custom Validator belongs to on the pageprivatestring pVgroup;
 //Extensions you allow to be uploadedprivate string[] pFileTypeRange;
 //Boolean indicator to check if file extension is allowedprivatebool Ind = false;
 //The Image Minimum Widthprivateint minWidth = 0;
 /* * Get and Sets for the 上面 private variables.
 * */publicbool GotFile
 {
 get { return pGotFile; }
 }
 publicstring FileExt
 {
 get { return pFileExt; }
 }
 public HttpPostedFile FilePost
 {
 get { return pFilePost; }
 }
 publicbool Required
 {
 set { pRequired = value; }
 }
 publicstring Vgroup
 {
 set { pVgroup = value; }
 }
 publicstring FileTypeRange
 {
 set { pFileTypeRange = value.ToString().Split(','); }
 }
 publicint MinWidth
 {
 set { minWidth = value; }
 }
 protectedvoid Page_Load(object sender, EventArgs e)
 {
 //here we assign the validation group to the Custom Validator, //which I have inefficiently named ErrorMsg ErrorMsg.ValidationGroup = pVgroup;
 }
 protectedvoid ErrorMsg_ServerValidate(object source, 
 ServerValidateEventArgs args)
 {
 if (FilUpl.HasFile)
 {
 pGotFile = true;
 pFileExt = GetExtension(FilUpl.PostedFile.FileName);
 pFilePost = FilUpl.PostedFile;
 foreach (string str in pFileTypeRange)
 {
 if (str == pFileExt)
 {
 Ind = true;
 }
 }
 if (!Ind)
 {
 args.IsValid = false;
 ErrorMsg.Text = "The file format you specified is not supported";
 //Stop the functionreturn;
 }
 if (minWidth >0)
 {
 //If you get here then you have set//the MinWidth because you are expecting an image,//and due to validation once at this stage in the code,//we know that the user has uploaded some sort of image type System.Drawing.Image CheckSize = 
 System.Drawing.Image.FromStream(FilUpl.PostedFile.InputStream);
 if (CheckSize.PhysicalDimension.Width < minWidth)
 {
 args.IsValid = false;
 ErrorMsg.Text = "Your image does not meet the minimum width" + 
 "requirements which are" + minWidth.ToString() +"px";
 //Stop the functionreturn;
 }
 }
 }
 else {
 //So if we get here the user has not browsed for a file pGotFile = false;
 //If you have stated that the user has to browse for a file.//then we must stop now and inform the user of such.if (pRequired)
 {
 args.IsValid = false;
 ErrorMsg.Text = "You must upload something";
 }
 }
 }
 ///<SUMMARY>/// This returns the file extension. It does not contain the preceding full stop/// so it would return jpg and NOT. jpg. Please adjust your coding accordingly.///</SUMMARY>///<PARAMname="FileName">string</PARAM>///<RETURNS>string: the file extension e.g. jpg</RETURNS>privatestring GetExtension(string FileName)
 {
 string[] split = FileName.Split('.');
 string Extension = split[split.Length - 1];
 return Extension;
 }
}

最后更新的标签

内联我的更新代码,下面是我在定制标签中实现它的方法。

我现在用不同的标签前缀,这次我用的是不同的标记前缀:

<%@RegisterTagPrefix="ARDesigns"TagName="IUpload"Src="CustomControl.ascx"%>

,然后标记自身:

<ARDesigns:IUploadID="MyUpload1"runat="server"Vgroup="Val1"FileTypeRange="jpg,gif,png,bmp"MinWidth="400"/>

从 3 2006年09月 更新效果

基本上,我需要把这个放到我昨天tripped的时候。 简单,但却 slipped。 我们可以使用大写文件扩展名文件,因此我们需要将它的设置为小写,以便进行比较:换句话说,:

pFileExt = GetExtension(FilUpl.PostedFile.FileName).ToLower();

WEB  INT  文件  控制  上传  文件上传  
相关文章