正则表达式验证器表现得很奇怪

时间:2013-07-25 01:39:04

标签: c# asp.net file-upload asp.net-ajax

我有一个Web应用程序,允许用户发送最多5个jpg图像的报告。不知何故,我设法让用户发送最多5个jpg图像的报告。但是在用一些jpg图像提交报告之后发生了一些奇怪的事情,fileupload的正则表达式验证器(用户以前用jpg图像插入的文件上载)提示错误消息“只允许jpg文件”,我不知道出了什么问题在我的代码中。请帮我看看下面的代码。谢谢!

Aspx Page

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language = "Javascript">
function tbLimit() {
    var tbObj = event.srcElement;
    if (tbObj.value.length == tbObj.maxLength * 1) return false;
}
function tbCount(visCnt) {
    var tbObj = event.srcElement;
    if (tbObj.value.length > tbObj.maxLength * 1) tbObj.value = tbObj.value.substring(0, tbObj.maxLength * 1);
    if (visCnt) visCnt.innerText = tbObj.maxLength - tbObj.value.length;
}
</script>

<div id="headerbody">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server"
    TargetControlID="btnCancel"
    ConfirmText="Are you sure you want to cancel this report?"
    Enabled="true"/>

<asp:ConfirmButtonExtender ID="ConfirmButtonExtender2" runat="server"
    TargetControlID="btnReport"
    ConfirmText="False report may lead to disciplinary action!"
    Enabled="true"/>

<table width="100%">
    <tr>
        <td colspan="2">
            <h2 align="center">Report</h2>
        </td>
    </tr>

    <tr>
        <th class="auto-style1" align="right">
            <asp:Label ID="Label3" runat="server" Text="Type of Crimes:"></asp:Label>
            <br />
        </th>
        <td align ="left">
            <asp:DropDownList ID="ddlTOC" runat="server" style="margin-left: 25px" Width="150px">
            <asp:ListItem>Theft</asp:ListItem>
            <asp:ListItem>Loan Shark</asp:ListItem>
            <asp:ListItem>Robbery</asp:ListItem>
            <asp:ListItem>Gang</asp:ListItem>
            <asp:ListItem>Vandalism</asp:ListItem>
            <asp:ListItem>Accident</asp:ListItem>
            </asp:DropDownList>
            <br />
        </td>
    </tr>

    <tr>
        <th class="auto-style1" align="right">
            <asp:Label ID="Label4" runat="server" Text="Address:"></asp:Label>
            <br />
        </th>
        <td align ="left">
            <asp:TextBox ID="txtLocation" runat="server" style="margin-left: 25px" Width="400px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvLocation" runat="server" 
            ErrorMessage="Please enter the crime location." 
            ControlToValidate="txtLocation" Display="None">
            </asp:RequiredFieldValidator>
            <asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server"
            TargetControlID="rfvLocation" >
            </asp:ValidatorCalloutExtender>
            <br />
        </td>
    </tr>

    <tr>
        <th class="auto-style1" align="right">
            <asp:Label ID="Label5" runat="server" Text="Date & Time:"></asp:Label>
            <br />
        </th>
        <td align ="left">
            <asp:Label ID="lblDateTime" runat="server" Text=""></asp:Label>
            <br />
        </td>
    </tr>

    <tr>
        <th class="auto-style1" align="right">
            <asp:Label ID="Label6" runat="server" Text="Detail:"></asp:Label>
            <br />
        </th>
        <td align ="left">
            <asp:TextBox ID="txtDetail" runat="server" Height="75px" TextWrapping="Wrap" TextMode="MultiLine" Width="400px" style="margin-left: 25px"/>
            <asp:RequiredFieldValidator ID="rfvDetail" runat="server" 
            ErrorMessage="Please enter detail of the crime." 
            ControlToValidate="txtDetail" Display="None">
            </asp:RequiredFieldValidator>
            <asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" runat="server"
            TargetControlID="rfvDetail" >
            </asp:ValidatorCalloutExtender>

            <br />
            You have <asp:Label ID="lblCount" runat="server" Text="500"></asp:Label> &nbsp;characters left.
            <br />
        </td>
    </tr>

    <tr>
        <th class="auto-style1" align="right">
            <asp:Label ID="Label7" runat="server" Text="Picture:"></asp:Label>
            <br /> 
        </th>
        <td align ="left">
            <asp:FileUpload ID="FileUpload1" runat="server" style="margin-left: 25px"/>
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1"   
            ControlToValidate="FileUpload1" Runat="Server" ErrorMessage="Only jpg files are allowed"   
            ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$"/>
            <br />
            <asp:FileUpload ID="FileUpload2" runat="server" style="margin-left: 25px" />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator2"   
            ControlToValidate="FileUpload2" Runat="Server" ErrorMessage="Only jpg files are allowed"   
            ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$"/>
            <br />
            <asp:FileUpload ID="FileUpload3" runat="server" style="margin-left: 25px" />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator3"   
            ControlToValidate="FileUpload3" Runat="Server" ErrorMessage="Only jpg files are allowed"   
            ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$"/>
            <br />
            <asp:FileUpload ID="FileUpload4" runat="server" style="margin-left: 25px" />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator4"   
            ControlToValidate="FileUpload4" Runat="Server" ErrorMessage="Only jpg files are allowed"   
            ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$"/>
            <br />
            <asp:FileUpload ID="FileUpload5" runat="server" style="margin-left: 25px" Height="22px" Width="217px" />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator5"   
            ControlToValidate="FileUpload5" Runat="Server" ErrorMessage="Only jpg files are allowed"   
            ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$"/>
            <br />
        </td>
    </tr>

    <tr>
        <td colspan="2">
            <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
            <br />
        </td>
    </tr>

    <tr>
        <td colspan="2">
        <asp:Button ID="btnReport" runat="server" Text="Report" OnClick="btnReport_Click" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" CausesValidation="False" />
        <br />
        </td>
    </tr>
</table>
</div>
</asp:Content>
<asp:Content ID="Content2" runat="server" contentplaceholderid="head">
<style type="text/css">
    .auto-style1 {
        width: 469px;
    }
</style>
</asp:Content>

背后的代码

protected void btnReport_Click(object sender, EventArgs e)
    {
            String username = (String)Session["username"];
            String datetime = (String)Session["datetime"];
            String typeofcrime = ddlTOC.SelectedItem.Text;
            String location = txtLocation.Text;
            String detail = txtDetail.Text;

            // Read the file and convert it to Byte Array
            string filePath = FileUpload1.PostedFile.FileName;
            string filename = Path.GetFileName(filePath);
            string ext = Path.GetExtension(filename);

            string filePath2 = FileUpload2.PostedFile.FileName;
            string filename2 = Path.GetFileName(filePath2);
            string ext2 = Path.GetExtension(filename2);

            string filePath3 = FileUpload3.PostedFile.FileName;
            string filename3 = Path.GetFileName(filePath3);
            string ext3 = Path.GetExtension(filename3);

            string filePath4 = FileUpload4.PostedFile.FileName;
            string filename4 = Path.GetFileName(filePath4);
            string ext4 = Path.GetExtension(filename4);

            string filePath5 = FileUpload5.PostedFile.FileName;
            string filename5 = Path.GetFileName(filePath5);
            string ext5 = Path.GetExtension(filename5);

            string contenttype = String.Empty;
            string contenttype2 = String.Empty;
            string contenttype3 = String.Empty;
            string contenttype4 = String.Empty;
            string contenttype5 = String.Empty;

            //Set the contenttype based on File Extension
            switch (ext)
            {
                case ".jpg":
                    contenttype = "image/jpg";
                    break;
            }
            switch (ext2)
            {
                case ".jpg":
                    contenttype2 = "image/jpg";
                    break;
            }
            switch (ext3)
            {
                case ".jpg":
                    contenttype3 = "image/jpg";
                    break;
            }
            switch (ext4)
            {
                case ".jpg":
                    contenttype4 = "image/jpg";
                    break;
            }
            switch (ext5)
            {
                case ".jpg":
                    contenttype5 = "image/jpg";
                    break;
            }

                //insert the file into database
                string strQuery = "insert into MemberReport(username, typeofcrime, location, crdatetime, citizenreport)" +
                   " values ('" + username + "','" + typeofcrime + "','" + location.Trim() + "','" + datetime + "','" + detail.Trim() + "')";
                SqlCommand cmd = new SqlCommand(strQuery);
                InsertUpdateData(cmd);

                using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security= SSPI"))
                {
                    connAdd.Open();
                    var sql = "Select memberreportid From MemberReport Where crdatetime = '" + datetime + "'";
                    using (var cmdAdd = new SqlCommand(sql, connAdd))
                    {
                        SqlDataReader dr;
                        dr = cmdAdd.ExecuteReader();
                        if (dr.Read())
                        {
                            Session["memberreportid"] = dr["memberreportid"].ToString();
                        }
                    }
                    connAdd.Close();

                    connAdd.Open();
                    sql = "insert into AdminAssign(memberreportid) values ('" + Session["memberreportid"] + "')";
                    using (var cmdAdd = new SqlCommand(sql, connAdd))
                    {
                        cmdAdd.ExecuteNonQuery();
                    }
                    connAdd.Close();
                }

                if(contenttype.Equals("image/jpg"))
                {
                    System.Drawing.Image uploaded = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);

                    System.Drawing.Image newImage = new Bitmap(1024, 768);
                    using (Graphics g = Graphics.FromImage(newImage))
                    {
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(uploaded, 0, 0, 1024, 768);
                    }

                    byte[] results;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
                        EncoderParameters jpegParms = new EncoderParameters(1);
                        jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
                        newImage.Save(ms, codec, jpegParms);
                        results = ms.ToArray();
                    }

                    string sqlImage = "update MemberReport set image1 = @Data where memberreportid = '" + Session["memberreportid"] + "'";
                    SqlCommand cmdImage = new SqlCommand(sqlImage);
                    cmdImage.Parameters.AddWithValue("@Data", results);
                    InsertUpdateData(cmdImage);
                }

                if (contenttype2.Equals("image/jpg"))
                {
                    System.Drawing.Image uploaded2 = System.Drawing.Image.FromStream(FileUpload2.PostedFile.InputStream);

                    System.Drawing.Image newImage2 = new Bitmap(1024, 768);
                    using (Graphics g = Graphics.FromImage(newImage2))
                    {
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(uploaded2, 0, 0, 1024, 768);
                    }

                    byte[] results2;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
                        EncoderParameters jpegParms = new EncoderParameters(1);
                        jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
                        newImage2.Save(ms, codec, jpegParms);
                        results2 = ms.ToArray();
                    }

                    string sqlImage2 = "update MemberReport set image2 = @Data2 where memberreportid = '" + Session["memberreportid"] + "'";
                    SqlCommand cmdImage2 = new SqlCommand(sqlImage2);
                    cmdImage2.Parameters.AddWithValue("@Data2", results2);
                    InsertUpdateData(cmdImage2);
                }

                if (contenttype3.Equals("image/jpg"))
                {
                    System.Drawing.Image uploaded3 = System.Drawing.Image.FromStream(FileUpload3.PostedFile.InputStream);

                    System.Drawing.Image newImage3 = new Bitmap(1024, 768);
                    using (Graphics g = Graphics.FromImage(newImage3))
                    {
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(uploaded3, 0, 0, 1024, 768);
                    }

                    byte[] results3;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
                        EncoderParameters jpegParms = new EncoderParameters(1);
                        jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
                        newImage3.Save(ms, codec, jpegParms);
                        results3 = ms.ToArray();
                    }

                    string sqlImage3 = "update MemberReport set image3 = @Data3 where memberreportid = '" + Session["memberreportid"] + "'";
                    SqlCommand cmdImage3 = new SqlCommand(sqlImage3);
                    cmdImage3.Parameters.AddWithValue("@Data3", results3);
                    InsertUpdateData(cmdImage3);
                }

                if (contenttype4.Equals("image/jpg"))
                {
                    System.Drawing.Image uploaded4 = System.Drawing.Image.FromStream(FileUpload4.PostedFile.InputStream);

                    System.Drawing.Image newImage4 = new Bitmap(1024, 768);
                    using (Graphics g = Graphics.FromImage(newImage4))
                    {
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(uploaded4, 0, 0, 1024, 768);
                    }

                    byte[] results4;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
                        EncoderParameters jpegParms = new EncoderParameters(1);
                        jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
                        newImage4.Save(ms, codec, jpegParms);
                        results4 = ms.ToArray();
                    }

                    string sqlImage4 = "update MemberReport set image4 = @Data4 where memberreportid = '" + Session["memberreportid"] + "'";
                    SqlCommand cmdImage4 = new SqlCommand(sqlImage4);
                    cmdImage4.Parameters.AddWithValue("@Data4", results4);
                    InsertUpdateData(cmdImage4);
                }

                if (contenttype5.Equals("image/jpg"))
                {
                    System.Drawing.Image uploaded5 = System.Drawing.Image.FromStream(FileUpload5.PostedFile.InputStream);

                    System.Drawing.Image newImage5 = new Bitmap(1024, 768);
                    using (Graphics g = Graphics.FromImage(newImage5))
                    {
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(uploaded5, 0, 0, 1024, 768);
                    }

                    byte[] results5;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
                        EncoderParameters jpegParms = new EncoderParameters(1);
                        jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
                        newImage5.Save(ms, codec, jpegParms);
                        results5 = ms.ToArray();
                    }

                    string sqlImage5 = "update MemberReport set image5 = @Data5 where memberreportid = '" + Session["memberreportid"] + "'";
                    SqlCommand cmdImage5 = new SqlCommand(sqlImage5);
                    cmdImage5.Parameters.AddWithValue("@Data5", results5);
                    InsertUpdateData(cmdImage5);
                }

            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text = "Report Sent!";

            txtDetail.Text = "";
            txtLocation.Text = "";
    }

1 个答案:

答案 0 :(得分:1)

我在你的正则表达式中看到了几个问题。

  1. 您应该简单地使用不区分大小写的模式,而不是执行与{jpG不匹配的jpg|JPG。或者,如果所有其他方法都失败了,(j|J)(p|P)(g|G)
  2. 默认情况下,正则表达式中的.是任何字符的通配符。因此,即使是以tjpg结尾的文件也会被接受。你想逃避这一点。用反斜杠。
  3. 这看起来像一个讨厌的正则表达式只是为了验证文件名。更好的事情是这样的:^[^x]+\.jpg$其中x是无效的路径字符。或者,如果你想完全裸露,^\.jpg$之类的东西将确保只允许带有jpg ext的文件。 (再次在这里:观察不区分大小写。)
  4. 应用程序本身的几个问题:

    1. 字符串比较区分大小写。所以在你的switch语句中,“JPG”的ext不会匹配任何情况(我假设你最终会提供对更多文件类型的支持,否则一个开关在那里没有意义,应该用if替换)。在测试之前,您应该首先将ext转换为全部小写。
    2. 内容类型没有实际验证。我可以使用.jpg分机保存GIF,或病毒,您的系统会很乐意接受并存储它。
    3. 与2相同,但文件大小。
    4. 您正在使用字符串concat构建SQL查询。 这是一个很大的禁忌。它可能(读取:会)导致您的网站被SQL注入黑客摧毁。将准备好的语句用于所有内容
    5. 正则表达式应解决您的问题,但请考虑我指出的其他问题。