calling C# function immediately file is selected in fileupload - asp.net

I have a web form(asp.net) which I'm using to upload file. In current situation if a user choose a text file from their computer they have to click a buttton to upload the text in a box. I'm trying to find a way to skip the step with a button pressing.
How to call a C# function when the file is selected from user ?

Try this
<asp:FileUpload ID="FileUpload01" ClientIDMode="Static" onchange="this.form.submit()" runat="server"/>
in code behind Page_load event
if (IsPostBack && FileUpload01.PostedFile != null)
{
if (FileUpload01.PostedFile.FileName.Length > 0)
{
FileUpload01.SaveAs(Server.MapPath("~/Images/") + FileUpload01.PostedFile.FileName);
imguser.ImageUrl = "~/Images/" + FileUpload01.PostedFile.FileName;
}
}

Related

ASP.NET using Button instead of FileUpload to upload files

I'm trying to upload a file with Button element using hidden FileUpload element with ASP.NET using this snippet:
protected void Page_Load(object sender, EventArgs e)
{
Button2.Attributes.Add("onclick", "document.getElementById('" + FileUpload1.ClientID + "').click();");
}
My Button has Id = "Button2", FileUpload Id = "FileUpload1". Clicking on the button Windows Explorer opens successfully to upload files but FileUpload.HasFile still returns false in further code (no file gets loaded even though explorer gets opened and file is selected).
What is the cause of this problem and how to fix it?
Well, I suppose you want to hide the the FileUpload Control and still be able to upload the files.
Follow the following steps to achieve the required:
Place a FileUpload Control with the class hidden. Like below:
<style>
.hidden{
display: none;
}
</style>
<asp:FileUpload runat="server" ID="FileUpload1" CssClass="hidden" />
Then place a Button that will be visible to client and will handle the Javascript events
<asp:Button runat="server" ID="Button1" Text="Upload File" OnClick="Button1_Clicked" />
Add the Javascript events to handle things
$(document).ready(function(){
// This event will help click the FileUpload control
$('#<%= Button1.ClientID %>').on('click', function(){
$('#<%= FileUpload1.ClientID %>').click();
return false; // important to return false, so it does not posts back yet.
});
$('#<%= FileUpload1.ClientID %>').on('change', function(){ // To see if the file selection was changed and the user has selected something
if($(this).val() == ''){
alert('No file selected');
return false;
}
if(confirm('Do you want to upload this file? ' + $(this).val())){
__doPostBack('<%= Button1.ClientID %>', ''); // this will postback to the server click event
}
});
});
Now, handle the uploaded file.
public void Button1_Clicked(object sender, EventArgs e)
{
// Handle your upload function
var hasFile = FileUpload1.HasFile;
}
PS: It was a rough Idea, the code is not tested so it might need some love.

How to validate ajax toolkit AsyncFileUpload Control file size and extension before upload

I have am AsyncFileUpload Control like this
<ajaxToolkit:AsyncFileUpload
OnUploadedComplete="Attachment1_UploadedComplete"
OnClientUploadStarted="Attachment1_UploadStarted" runat="server"
ID="Attachment1File" AutoPostBack="true"
UploaderStyle="Traditional" CssClass="form-control"
UploadingBackColor="#CCFFFF" ThrobberID="loader1" />
I want allowed files to be doc,docx,pdf,xls,xlsx,zip and max file upload 10MB. How can I validate file before uploading?
I tried to do something like this in the codebehind but the file is already uploaded to the server when this executes
AttachmentError1.Visible = false;
string[] extension = Attachment1File.PostedFile.FileName.Split('.');
if (Attachment1File.PostedFile.ContentLength > 100000000 || !Extensions.Contains(extension[extension.Length-1]))
{
File.Delete(Server.MapPath("~/FormTemporaryFiles/") + FormId + "\\" + FormIdNumber.Value + "\\" + e.FileName.ToString());
Attachment1File.ClearAllFilesFromPersistedStore();
AttachmentError1.Visible = true;
}
Edit: I tried to use a custom validator but it didn't work.
What I did is add the code to the codebehind in the UploadedCompleted Event of the AsyncFileUpload and chech again at the button submit. Custom Validator did not work, so I had to do it manually.

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.

Login by hitting enter key in asp.net Login control

I must have read a hundred forum and blogposts about this, all talking about placing a Panel and setting the Default button to the Login button, or setting the Default button in the Form. I've tried all this plus lots more, but nothing works.
I have two LinkButtons in my Login control, which is converted to a template. The first is the Login button, the second is a link to a register page. When I hit enter, the Register LinkButton fires and redirects to the register page.
I've tried setting the default button on panels and placing them everywhere and setting the default button in the Form tag itself. I tried removing the Register button and setting an onclick on the and calling a function that redirected to the register page. That didn't even work, and the enter key still redirected to the register page.
They are placed in the LayoutTemplate like this:
<div class="btn-login">
<asp:LinkButton ID="LoginButton" runat="server" CommandName="Login" ValidationGroup="LoginUserValidationGroup"
Height="38px" Width="120px">
</asp:LinkButton>
</div>
<div class="btn-opretbruger">
<asp:LinkButton ID="Register" runat="server" ValidationGroup="LoginUserValidationGroup"
Height="38px" Width="120px" PostBackUrl="/Account/registrerbruger.aspx">
</asp:LinkButton>
</div>
All the articles I have read used Button controls, and I use a LinkButton.
Any ideas?
Task 1)
Add some scrip to your page to disable the enter key...
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
Task 2)
Add some script that allows you to target a html element and raise the event handler for it
function submitByTarget(event, target) {
if (event.keyCode == 13) {
jQuery('#' + target.id).click();
}
}
Task 3)
Add an event handler for your login txtbox that waits for the enter key to be hit and raises the correct .click handler for the target button...in this case 'login'
txtLogin.Attributes.Add("onkeypress", "return submitByTarget(event," + btnSearch.ClientID + ");");
Include the following code in the page load even.It'll automatically set the focus on the button.
//Set the default button for the Login page
this.Page.Form.DefaultButton = btnLogin.UniqueID;

File upload control in 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"?

Resources