0

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

页面

<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 = "";
    }
4

1 回答 1

1

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

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

以及应用程序本身的几个问题:

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

正则表达式应该可以解决您的问题,但请考虑我指出的其他问题。

于 2013-07-25T02:05:13.270 回答