File upload control in ASP.NET - asp.net

i am using file upload control in ASP.NET for uploading images.
In my form there are two buttons.one for assigning criteria which redirects to other form and other for submitting form.
After assigning criteria only the user has to use submit button.
My problem is when is upload image and click on AssignCriteria button and return back to original page,the upload control is getting blank.
How to keep that upload image control value in that textbox even if we redirected to other page and come back.

<asp:FileUpload runat="server" ID="uploadStatement" />
<asp:Button runat="server" Text="Upload" OnClick="cmdUpload_Click" />
Next code uploads selected file to Temp folder on the server, in my case - parses it and deletes the file.
protected void cmdUpload_Click(object sender, EventArgs e)
{
var fileName = Server.MapPath(Path.Combine("Temp", String.Concat(Guid.NewGuid().ToString(), Path.GetExtension(uploadStatement.FileName))));
try
{
uploadStatement.SaveAs(fileName);
// parse file
}
finally
{
File.Delete(fileName);
}
}

Since any manipulation with the "input type='file'" element is a serious security threat I am afraid there is no way to do this.
Have you considered using of some AJAX overlay "dialog"?

Related

Validating ASP.NET FileUploader with CustomValidator

I have a FileUpload control to upload a certificate file. The user has to upload the file the first time, in subsequent visits to the page, we display the certificate content on the page, so it's not necessary to upload a file again.
Now I want to validate that a certificate is uploaded at least at once. The rest of the page uses ASP.NET validation controls so I want to go ahead with the same.
I can't use a RequiredFieldValidator on the FileUpload, because then it will fire everytime I try to save the page, which is wrong.
I tried using a CustomValidator and used the serverside validation, but seems that too fires only if I click on the file uploader. If I just leave it alone, the server side validation is not triggered.
I can of course do the validation on the [Save] button click event, but is there a proper way to do that using the validator events themselves?
CustomValidator:
<asp:CustomValidator ID="cusCertifacteExistanceValidator" runat="server" ValidationGroup="ConfigValidation" CssClass="errorMsg" ControlToValidate="fcertificate" Enabled="false" ErrorMessage="Certificate is not available" OnServerValidate="ValidateCertificateUpload">*</asp:CustomValidator>
CustomValidator Server side validation:
protected void ValidateCertificateUpload(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
var existingCertificate = string.Empty;
if (ViewState["loginProviderProperties"] != null)
{
existingCertificate = ((List<Configuration>)ViewState["properties"]).Find(p => p.Name == "certificate").Value;
}
if (fX509Certificate.HasFile || existingCertificate != string.Empty)
{
args.IsValid = true;
}
}
It is very dificult to imagine without the code but My guess would be to add
ValidateEmptyText="true"
to custom validator.

Implementing reCaptcha in ASP.NET

I am trying to insert a captcha in my ASP.NET code. Basically, in the lbt_proceed_click() method, I want the browser to proceed to the next page using Response.Redirect("foo") only if the captcha entered is correct.
I searched, but could not find a solution, especially since I am not using a form to send data, but writing to a database directly, and then moving to the next page using Response.Redirect().
go to the reCAPTCHA site and register for a unique key
Download reCAPTCHA .NET Library
Create and Save your Public and Private keys safely
In the website we add a reference to library/bin/Release/Recaptcha.dll
after the #Page directive, insert the following code:
<%# Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha"%>
add control in asp.net tag:
<recaptcha:RecaptchaControl
ID="recaptcha"
runat="server"
PublicKey="Your very own public key here"
PrivateKey="Your very own privat key here"
/>
add button and label to your form
add the following button click method(btnSubmit_Click) in code behind file :
if (Page.IsValid)
{
lblResult.Text = "You Got It!"; // Or Use Response.redirect("foo");
}
else
{
lblResult.Text = "Incorrect";
}
Test your Page!

Update an image control as soon as a file is selected in File Upload control in ASP.NET

I have an image control and a file upload control in .NET 2.0 (VS.NET 2008) form. As soon as user selects an image file in the file upload control, i want the image to appear in the image control of the form. What would be the way to do this ?
(The only event File Upload seems to support is 'OnChange' and i don't know enough javascript to update Image1.URL based on content of FileUpload).
Thanks,
Chak.
You need to upload Asynchronously , and you could try AJAX AsyncFileUpload and this is what you are looking...
http://asp.net-informations.com/ajax/ajax-AsyncFileUpload.htm
Are you looking for a kind of preview? You can only show the image to the user after the file has been uploaded. I'm pretty sure the user has to actively do so (otherwise you could try to read the entire filesystem from the browser)
I think this is a good example:
http://www.codeproject.com/KB/ajax/AJAXUpload.aspx
this is a good starting point too:
http://www.eggheadcafe.com/community/aspnet/2/10204276/how-to-display-image-when-upload-image.aspx
or here:
http://www.eggheadcafe.com/community/aspnet/2/10236947/image-upload-and-display.aspx
updated
protected void Button4_Click(object sender, EventArgs e)
{
string strExtn;
string strpostedfile;
strpostedfile = fileuploading.PostedFile.FileName;
strExtn = System.IO.Path.GetExtension(strpostedfile);
strExtn = strExtn.ToLower();
string strEx = Path.GetExtension(fileuploading.PostedFile.FileName).ToLower();
String filename = Path.GetFileName(fileuploading.FileName);
filename = filename.Remove(filename.Length - strEx.Length);
fileuploading.SaveAs(Server.MapPath("~/Photos/") + filename);
uploadImage.ImageUrl = "~/Photos/" + filename;
}
Page:
<asp:FileUpload ID="fileuploading" runat="server" />
<asp:Button ID="Button4" runat="server" onclick="Button4_Click" Text="Button" />
<br />
<asp:Image ID="uploadImage" runat="server" />

UpdatePanel resetting object to inital state

I have an application that I am currently writing that works by iterating through nodes, and then updating the page with the information of the current node. I have an UpdatePanel in the page which contains a label, textbox, and a button. The label lists the currently available children of the current node, the user enters in which child they want to go to into the textbox, and then hits the submit button. I set the new value of the node in the submit button's event handler.
Here's my problem: Every time I enter in which node I want to navigate to, the object resets its value to the value it was initially initialized to. I have even put this same code into a Windows Form to validate that it's working correctly to iterate through my tree, and it works as it should, so I know my problem is AJAX-related.
This is the first app that I have written using AJAX, so I am still in the process of learning how it works. Any help would be greatly appreciated. I have Googled and searched SO through and through.
Here is the HTML:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="question" runat="server" Text=""></asp:Label>
<br />
<asp:TextBox ID="answer" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Submit" runat="server" Text="Submit" onclick="Submit_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
And the C#:
protected void Submit_Click(object sender, EventArgs e)
{
int ans = int.Parse(answer.Text);
if (!current.ChildIDs.Contains(ans))
{
return;
}
current = tree.Node(ans);
question.Text = current.Question;
}
current is the current node, which has a public ArrayList of all of its children's IDs. tree is the NodeTree I have; calling Node just returns the new node. Both current and Tree get initialized in the Page_Load event, and that only fires once (when the page is first loaded).
It's really pretty simply code; I'm just having difficulty understanding why the AJAX isn't working correctly.
I have even put this same code into a
Windows Form to validate that it's
working correctly to iterate through
my tree, and it works as it should, so
I know my problem is AJAX-related.
It sounds like you're expecting ASP.NET to remember what the object current is between requests, since that's how Windows forms applications work.
Web applications are stateless - after each request, ASP.NET discards all your variables. To access the variable during a subsequent request, you have to either:
1) Send enough data with the request to reconstruct the variable. You can do this using a querystring parameter or an HTML form value (the hidden fields another response mentioned).
2) Save the variables in a Session store (which can be in-memory or backed by a database).
3) Store the value in a coookie.
Of these three, it's easiest to show you how to use Session, given what you've shared in your question. However, beware: session has its risks - by default, ASP.NET session objects are stored in-memory, and it's a potential security hazard. But here's how you should be able to get your application to work.
// In your Page_Load code that initializes your 'current' variable
// When the user first requests the page, create a new Node
if (! this.IsPostBack)
{
Node current = new Node(); //
Session("currentNode") = current;
}
// When the user clicks a button on the page (posts), use the
// node in session instead
else
{
current = Session("currentNode");
}
When you update non-form elements in the browser (labels, literals, etc.), .NET is unable to see any of the changes you've made.
Try adding a hidden input for each label that records the new value. Then within the method you have wired up to the button's OnClick event, do something like this:
myLabel.Text = myHiddenInput.value;
I think you just need to tell the updatepanel to update itself. Try this:
protected void Submit_Click(object sender, EventArgs e)
{
int ans = int.Parse(answer.Text);
if (!current.ChildIDs.Contains(ans))
{
return;
}
current = tree.Node(ans);
question.Text = current.Question;
UpdatePanel.Update();
}

FormView + FileUpload - can I change a bound field based on the fileupload?

I have a FormView control in an ASP.NET 2.0 app. I've got the database storing a filename (a person's picture) in a column. I can't bind the value of the column to a fileupload control - so I'm trying to use a hidden form field. Here's what I have:
<asp:HiddenField ID="pictureLink" runat="server" Value='<%# Bind("pictureLink") %>' />
<asp:FileUpload ID="pic" runat="server" />
Code Behind:
//ItemUpdating event handler
void do_update(object sender, FormViewUpdateEventArgs e)
{
FileUpload newpic = (FileUpload)profile_edit.FindControl("pic");
if (newpic.HasFile)
{
//do a bunch of file uploading "stuff" which makes a new file name
e.Keys["pictureLink"] = new_filename;
}
}
My goal is to update the hidden form field's value to the newly updated file name so the database is properly updated.
I think I'm close - but it seems like I can't programmatically alter any of the bound data fields after-the-fact.
I've tried using javascript to change the control - but the new file name will actually be different than what they upload; which javascript can't necessarily "predict" and reliably put the correct file name into the hidden form field
Any suggestions?
Thanks
I think you might need to alter e.NewValues, not e.Keys. See the NewValues property on MSDN, it might point you in the right direction.
OK - I found the answer not too long after I posted the question. I'll leave it open in case someone has a better (more elegant) solution. Basically, I change the do_update event handler to intercept the file upload. If there's a file, then I edit the NewValues collection so that the database receives the new file name instead of the old one.
//ItemUpdating event handler
void do_update(object sender, FormViewUpdateEventArgs e)
{
FileUpload newpic = (FileUpload)profile_edit.FindControl("pic");
if (newpic.HasFile)
{
//do a bunch of file uploading "stuff" which makes a new file name
//HERE IS THE CHANGE - update the newvalues object to the new file name
e.NewValues[1] = new_filename;
}
}

Resources