pop up alert

J

James Page

I have a aspx page where the user selects a image to upload to a sql
database. In the code behind on the item_inserting event i am halting the
insert event if the user has not selected an image file. Here's the select
case code:

Select Case fileExtension
Case ".gif"
MIMETypePic = "image/gif"
Case ".jpg", ".jpeg", ".jpe"
MIMETypePic = "image/jpeg"
Case ".png"
MIMETypePic = "image/png"

Case Else

e.Cancel = True
Exit Sub
End Select

What i'd like to do is alert the user with a pop up box that the file was
not a valid image file. I think this requires some form of clientside script.
can anybody advise how to do this?
 
C

Cowboy \(Gregory A. Beamer\)

There are a couple of ways to handle this. The down and dirty way is
something like this:

Dim builder as new StringBuilder

builder.Append("<script type='JavaScript'>");
builder.Append(CrLf);


builder.Append("alert('")
'Separated here for Select Case
builder.Append("invalid graphics type")

builder.Append("');")
builder.Append(CrLf)

builder.Append("</script>")

Dim lit as new LiteralControl(builder.ToString())

Panel1.Controls.Add(lit)

You then add a Panel to the page where you want the message to show up.

There are other ways to accomplish this. One is to have a set JavaScript
function that you write the code to fire only when there is a mistake in
type. Your upload control can also Emit JavaScript when there is a problem.
 
J

James Page

Thanks guys this is what i've come up with:

Private Sub MessageBox(ByVal strMsg As String)

Dim lbl As New Label()
lbl.Text = "<script language='javascript'>" & Environment.NewLine &
"window.alert('" + strMsg + "')</script>"
Page.Controls.Add(lbl)

End Sub

......

Select Case extensionPic
Case ".gif"
MIMETypePic = "image/gif"
Case ".jpg", ".jpeg", ".jpe"
MIMETypePic = "image/jpeg"
Case ".png"
MIMETypePic = "image/png"

Case Else
MessageBox("Product picture:\r\nOnly .gif, .jpg and .png
file types\r\ncan be selected for upload to database.")
UploadedFilePic.Focus()
e.Cancel = True
Exit Sub
End Select


Any comments?
 
B

bruce barker

check on client before submit (could use a custom validator).


string script = @"
function filetest() {
var f = document.getElementById('"+fileupload.ClientID+@"');
if (!/\.(gif|jpg|jpeg|png)$/.text(f.value)) {
alert('Invalid file extension');
return false;
}
}
"
Page.ClientScript.RegisterStartupScript(this.GetType(),
"check",
script,
true);
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(),
"check",
"if(!filetest())return false;");
 
J

James Page

Which event - page load?

bruce said:
check on client before submit (could use a custom validator).


string script = @"
function filetest() {
var f = document.getElementById('"+fileupload.ClientID+@"');
if (!/\.(gif|jpg|jpeg|png)$/.text(f.value)) {
alert('Invalid file extension');
return false;
}
}
"
Page.ClientScript.RegisterStartupScript(this.GetType(),
"check",
script,
true);
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(),
"check",
"if(!filetest())return false;");
 
M

Mark Rae [MVP]

lbl.Text = "<script language='javascript'>" & Environment.NewLine &

Once again...

lbl.Text = "<script type=""text/javascript"">" & Environment.NewLine &

The language tag has been deprecated for some time...
MessageBox

Will someone be logged on to the server to see that...?
 
J

James Page

Thanks I'll change that.

Logged on??
Once again...

lbl.Text = "<script type=""text/javascript"">" & Environment.NewLine &

The language tag has been deprecated for some time...


Will someone be logged on to the server to see that...?
 
M

Mark Rae [MVP]

Thanks I'll change that.

Logged on??

Yes - you are using MessageBox in your server-side code... For one thing,
shouldn't it be MessageBox.Show(...)? And where do you expect this message
box to display...?
 
C

Cowboy \(Gregory A. Beamer\)

Labels are not the best place to attach text, due to the order in which they
display. I am not completely convinced it will not work, but I still find
attaching to a Panel is better.

Also, you should note you are mixing server side code and client side. When
someone goes to upload, it will be a single request (multi-part) to the
server, which contains the form information, plus a binary representation of
image someone is uploading. Once you see it is the incorrect image, you are
finished with the server side code, which means your MessageBox() routine
cannot be contacted without creating a second trip to the server. This is
what Mark was talking about.

On your form submit routine, you should check for image type and then either
give the user a success message or a failure message (and/or popup). Do not
try to contact server side code from the client side, except through events.
 
P

Paul Shapiro

I've used a regular expression validator to check on the client before the
file is submitted.
<asp:FileUpload ID="FileUploadAbstract" runat="server" Width="450px" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server"
ControlToValidate="FileUploadAbstract"
ErrorMessage="Only .pdf files can be submitted"
ValidationExpression=".*\.pdf$"
Display="Dynamic">
</asp:RegularExpressionValidator>
<asp:Button ID="ButtonFileUpload" runat="server" Text="Submit PDF File"
OnClick="ButtonFileUpload_Click" />
Unless the file type is .pdf, the submit button remains unavailable.

On the server I check the mime type as a further verification before saving
the file, but unless the user is playing games, I think the client side
check would usually be sufficient.
Paul Shapiro
 
J

James Page

MessageBox is the subroutine that is called if the select case fails and
passes string back to it and display a client side alertbox.
Here's the full code:

Private Sub MessageBox(ByVal strMsg As String)
' define a javascript alertbox containing
' the string passed in as argument
' create a new label

Dim lbl As New Label()
' add the javascript to fire an alertbox to the label and
' add the string argument passed to the subroutine as the
' message payload for the alertbox
lbl.Text = "<script type=""text/javascript"">" &
Environment.NewLine & "window.alert('" + strMsg + "')</script>"
' add the label to the page to display the alertbox
Page.Controls.Add(lbl)

End Sub

Private Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.FormViewInsertEventArgs) Handles
FormView1.ItemInserting
'Reference the FileUpload control
Dim UploadedFilePic As FileUpload =
CType(FormView1.FindControl("fileUploadProdPict"), FileUpload)


'Make sure we are dealing with a JPG, GIF or PNG file
Dim extensionPic As String =
Path.GetExtension(UploadedFilePic.PostedFile.FileName).ToLower()
Dim filenamePic As String =
Path.GetFileName(UploadedFilePic.PostedFile.FileName)
Dim MIMETypePic As String = Nothing

Select Case extensionPic
Case ".gif"
MIMETypePic = "image/gif"
Case ".jpg", ".jpeg", ".jpe"
MIMETypePic = "image/jpeg"
Case ".png"
MIMETypePic = "image/png"

Case Else
MessageBox("Product picture:\r\nOnly .gif, .jpg and
..png file types\r\ncan be selected for upload to database.")
UploadedFilePic.Focus()
e.Cancel = True
Exit Sub
End Select

'Specify the values for the MIMEType and ImageData parameters
e.Values("productPicMimeType") = MIMETypePic
'Load FileUpload's InputStream into Byte array
Dim
imageBytesPic(UploadedFilePic.PostedFile.InputStream.Length) As Byte
UploadedFilePic.PostedFile.InputStream.Read(imageBytesPic, 0,
imageBytesPic.Length)
e.Values("productPic") = imageBytesPic
e.Values("productPicFileName") = filenamePic
End Sub

Therefore if the item Inserting event fails, at the select case stage,
the user is prompted to try again. I know its not the technically
correct solution but it does work. Ideally i'd like full client side
validation before the item inserting event is fired but javascript is
not my strong suit!
 
J

James Page

Thanks Paul

Two questions:

what is the expresssion syntax for checking multiple file types and how
do you get the validation message to refresh when the user has selected
the correct file type i.e.
1. User selects .doc
2. validation shows error
3. User tries again and selects .pdf
4 validation still shows error.
 
P

Paul Shapiro

I am not familiar enough with regEx syntax to give the correct version for
mutltiple file types, but I think it's straightforward to specify
alternates. So maybe something like ".*\.(pdf|doc|txt)$"?

The validation refresh is automatic. I didn't add any code for it.
 
J

james page

Paul -

I've discovered the syntax to check for file extension types prior to
upload - thought I'd post it to help others in the same boat I was in:

To check for .pdf files:

^.*(([^\.][\.][pP][dD][fF]))$

To check for (my original requirements) .pdf, .txt, .doc, zip & .jpg:

^.*(([^\.][\.][pP][dD][fF])|([^\.][\.][tT][xX][tT])|([^\.][\.][dD][oO][cC])|([^\.][\.][zZ][iI][pP])|([^\.][\.][jJ][pP][gG]))$

Works a treat!


My head hurts now - I'm going for a lie down!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top