2

I have to upload images into DB using file up-loader. I have used the given below code, but it is not working. If I upload any pdf or doc file that also inserting into DB and the error message also displaying. I want to stop insertion if the file is not an image format. Help me to find a proper solution. Thank you.

ASPX :

<asp:FileUpload ID="PhotoUpload1" runat="server" ForeColor="#999999" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" ErrorMessage="*jpeg,gif,png" ControlToValidate="PhotoUpload1" ForeColor="Red" 
ValidationExpression=".*\.([gG][iI][fF]|[jJ][pP][gG]|[jJ][pP][eE][gG]|[bB][mM][pP])$">
</asp:RegularExpressionValidator>


<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
2
  • you could use (?i) modifier to do a case insensitive match. Commented Dec 8, 2014 at 7:04
  • 1
    "(?i).*\.(gif|jpe?g|png|bmp)$" Commented Dec 8, 2014 at 7:05

2 Answers 2

5

This should work for jpg, png, gif and png.

UPDATED

/.*\.(gif|jpe?g|bmp|png)$/igm

You can check how it works here

Sign up to request clarification or add additional context in comments.

4 Comments

[e?] matches e or ?
@AvinashRaj did this to match both jpg and jpeg.
your regex matches jp?g also.
@AvinashRaj no it doesn't.
1

Try alternation "|" notation. And only list allowed file extensions (whitelist) like jpg,png.

<asp:FileUpload ID="PhotoUpload1" runat="server" ForeColor="#999999" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" ErrorMessage="*jpeg,gif,png" ControlToValidate="PhotoUpload1" ForeColor="Red" 
ValidationExpression="(.*png$)|(.*jpg$)|(.*jpeg$)">
</asp:RegularExpressionValidator>

Asp.Net validation need to be validated on server side too.

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
       //Note that there might be ServerSideValidation which evaluated to false.
       if (!Page.IsValid)  
         return;

       // Insert DB code here.
    }

2 Comments

I want insert only image file into DB. These answers are showing error message if the selected file is not a image format while clicking insert button, but the file also inserting into db
The given below code is used to insert data into DB. QA_Form2TableAdapters.tbl_QA_InstallationTableAdapter qa; qa =new QA_Form2TableAdapters.tbl_QA_InstallationTableAdapter(); qa.InsertAll(ddlState.Text, ddlDistrict.Text,PhotoUpload1.FileBytes);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.