Shu
Shu

Reputation: 55

Allow only .Jpg And .Jpeg

I need to upload only .Jpg and .Jpeg files but while uploading it also allows .gif , .pdf,.txt and all

Here is my file upload control with validation:

<td align="left" colspan="3">
 <asp:FileUpload ID="fuAttachment1" runat="server" />
 <asp:RegularExpressionValidator ID="revFile1" runat="server" ControlToValidate="fuAttachment1"
     Enabled="true" ErrorMessage="Invalid File. Please select valid file." ForeColor="Red"
    ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.JPG|.jpeg|.JPEG)$">*
  </asp:RegularExpressionValidator>
</td> </tr>

Upvotes: 0

Views: 150

Answers (3)

Harold Javier
Harold Javier

Reputation: 887

You can allow only JPEG files in your upload from Code-Behind.

In my example, I use DetailsView and FileUpload controls (in VB code)

Protected Sub DetailsView1_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles DetailsView1.ItemInserted
     If e.AffectedRows > 0 Then
         Dim results As DataView = CType(maxEmployeeIDDataSource.Select(DataSourceSelectArguments.Empty), DataView)
         Dim pictureIDJustAdded As Integer = CType(results(0)(0), Integer)
         Dim imageupload As FileUpload = CType(DetailsView1.FindControl("imageupload"), FileUpload)
         If imageupload.HasFile Then
             Dim baseDirectory As String = Server.MapPath("~/uploaded_images/")
             imageupload.SaveAs(baseDirectory & pictureIDJustAdded & ".jpg")
         End If
     End If
     End Sub



 Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting
     Dim cancelInsert As Boolean = False
     Dim imageupload As FileUpload = CType(DetailsView1.FindControl("imageupload"), FileUpload)
     If Not imageupload.HasFile Then
         cancelInsert = True
     Else
         If Not imageupload.FileName.ToUpper().EndsWith(".JPG") Then
             cancelInsert = True

        End If
     End If
     If cancelInsert Then
         e.Cancel = True

    End If

I hope this can help you.

Upvotes: 0

Rohit Surve
Rohit Surve

Reputation: 140

Try validation expression as follows

 ValidationExpression="(.*\.([Jj][Pp][Gg])|.*\.([Jj][Pp][Ee][Gg])$)"

Upvotes: 0

Raja.S
Raja.S

Reputation: 83

I think below expression will work try this

^.+\.(?:(?:[jJ][pP][eE][gG])|(?:[jJ][pP][gG]))$

Upvotes: 1

Related Questions