FileUpload.hasFile is always False - asp.net

I have a FileUpload control (and it's not inside an UpdatePanel) and its hasFile property is always False.
<asp:FileUpload ID="certificateUploader" runat="server"/>
Any thought?

Add a trigger for your UpdatePanel
<Triggers>
<asp:PostBackTrigger ControlID="btnCertificateUpload" />
</Triggers>
This will force a postback when the upload button is clicked.
Also, add the line below to the Page_Load
Page.Form.Attributes.Add("enctype", "multipart/form-data");

You cannot upload files using AJAX => you should not be placing a FileUpload control inside an UpdatePanel because this UpdatePanel sends an AJAX request to the server.

I also uploaded a file using the FileUpload control, but the HasFile property returned false. Turn out that FileUpload.HasFile is also false if you upload an empty file. In this case, adding some text to the file, you want to upload will make the Has file property return true.

To complement the example given by #dbFrameIT Support:
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Always" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="UploadButton" runat="server" Text="Upload Selected File" OnClick="UploadButton_Click" />
<asp:Label ID="UploadDetails" runat="server" Text=""></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="UploadButton" />
</Triggers>
</asp:UpdatePanel>
your code behind (c#)
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
UploadDetails.Text = "Please first select a file to upload...";
}
else
{
string FileName = FileUpload1.FileName;
UploadDetails.Text = string.Format(
#"Uploaded file: {0}<br />
File size (in bytes): {1:N0}<br />
Content-type: {2}",
FileName,
FileUpload1.FileBytes.Length,
FileUpload1.PostedFile.ContentType);
// Save the file
string filePath = Server.MapPath("~/Brochures/" + FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
}
}

the whole time it was about the permissions i had(or didn't have to be more specific) over the file am trying to upload, i granted the user the sufficient permissions and it all went well.
thanks a lot for your help and posts.

You can try to take your button off from the UpdatePanel;
As far as I get, UpdatePanels always update when something inside any other update panel updates, so if your button postback, your FileUpload control also postback and lose the file reference.

Sometimes fileUpload has problems. You can use simple input:
<input id="filMyFile" type="file" runat="server"></input>
In code save file to server:
HttpPostedFile myFile = filMyFile.PostedFile;
string fullPath=Server.MapPath("~/UploadDocuments/") + myFile.FileName;
myFile.SaveAs(fullPath);
And file will save at UploadDocuments folder in your ASP.NET application (server)

Related

Cannot Download file in UpdatePanel

The below code works which allows me to download a Word document.....
Try
Response.BufferOutput = True
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Charset = ""
HttpContext.Current.Response.ContentType = "application/msword"
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=myfile.doc")
HttpContext.Current.Response.Write(s)
'HttpContext.Current.Response.End()
HttpContext.Current.ApplicationInstance.CompleteRequest()
HttpContext.Current.Response.Flush()
Catch ex As Exception
Response.Write(ex.Message)
End Try
But as soon as i add an UpdatePanel - it doesnt download the file and no errors are generated? After reading around i added a trigger with the ControlID value set to the button that starts creating the Word doc file. I've tried several combinations of code but nothing seems to work. Any help on how to narrow this down? I've also debugged and no errors show. Ive checked my downloads folder - nothing there, tried setting no cache (Response.Cache.SetCacheability(HttpCacheability.NoCache)) and that didnt work. As soon as i remove the UpdatePanel then all seems to work?
<asp:UpdateProgress ID="ProgressUpdate" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<img alt="progress" src="../images/loading.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="buttonDownloadFile" />
</Triggers>
<ContentTemplate>
..
Completely lost on this one. Could anyone suggest a workaround or how to tackle this problem?
The accepted answer is just plain wrong. You need to register the control with the scriptmanager. Mine is in the master page and here is the code i use to register any button for proper post backs.
private void MasterPageRegisterButtonForPostBack(Control bt)
{
MasterPage masterPage = Master;
if (masterPage is MainMaster)
{
var mainMaster = masterPage as MainMaster;
if (bt != null && mainMaster.MasterScriptManager != null)
{
mainMaster.MasterScriptManager.RegisterPostBackControl(bt);
}
}
}
I got it working the following way:
inside my Update Panel I configured the controls that may forece a full postback in order to get the download working.
(I'm using also Master pages,this is the same solution as Steve's but registering it in the aspx and not in code behind)
<asp:UpdatePanel runat="server" ID="UpdatePanelDownload" UpdateMode="Conditional" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:LinkButton ID="LinkButtonDownload" OnClick="Download_Click" runat="Server">Save XML</asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="LinkButtonDownlod" />
</Triggers>
</asp:UpdatePanel>
I had to open an ashx Generic Handler in another window and passed some session variables to it, like filename, full path, etc.
I did it like this
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%foreach(var f in listOfObject){ %>
<a class="btn btn-danger" href="javascript:__doPostBack('ctl00$BodyContent$butDownload', '<%=f.ID %>')" >Download</a>
<%} %>
</ContentTemplate>
</asp:UpdatePanel>
<asp:LinkButton runat="server" ID="butDownload" OnClick="butDownload_Click" style="display:none;">LinkButton</asp:LinkButton>
///----Server-Side-----
protected void butDownload_Click(object sender, EventArgs e)
{
string strID = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(strID))
{
int id = int.Parse(strID);
//---Do what you want here
}
}
The UpdatePanel does not support file upload or download. There are tons of ajax-enabled components out there that will do this, Google is your friend.
EDIT: -
Some examples: -
http://forums.asp.net/t/1076322.aspx?How+to+create+a+flipcart+like+panel+for+showing+products+in+gridview - I like this approach, he injects an IFrame using JavaScript that points to a page responsible for downloading the file. Works inside an UpdatePanel
http://encosia.com/ajax-file-downloads-and-iframes/ - Similar approach

asp.net file upload inside formview always return false (not in updatepanel)

I am using fileupload control inside formview edittemplate
<asp:FileUpload ID="fileup_profilfoto" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Sadece şu formatlar (.jpg, .bmp, .png, .gif)" ValidationExpression="^.*\.(jpg|JPG|png|PNG|bmp|BMP|gif|GIF)$" ControlToValidate="fileup_profilfoto" ForeColor="#00C0CC"></asp:RegularExpressionValidator>
It was working.But I added an updatepanel then it didnt work,and then I remowed update panel.But it's still return false (hasfile)
protected void frmviewProfil_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
try
{
FileUpload fileup_profilfoto = (FileUpload)frmviewProfil.FindControl("fileup_profilfoto");
if (fileup_profilfoto.HasFile)
{
//do something
}
else
{
//do something
}
}
}
always goes else scopes.
hi use triggers to achive that
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional">
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label><br /><br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
code behind
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
Label1.Text = FileUpload1.FileName;
}
}
Did you do anything to the properties of the fileupload control, for example setting the autopost back value to false? Try setting this to true if it is false.
I came across this question when I had this problem and figured I'd post what my problem and solution were as well.
Make sure the file you are trying to upload is larger than 0 bytes. I was trying to upload some blank text files for testing and each file had the FileName property set correctly, but HasFile was always false. Adding some text to the files gave it some content and the file was able to be uploaded successfully.

asp.net set textbox control in panel contol

I want to set the textbox contol located in the panel control via code
I know to retrieve the inputted value in the textbox control:
string myVal = Request.Form["txtResult"];
I want to set the txtResult.text = "some text";
makeup snippet:
<asp:Panel ID="Panel1" runat="server" Style="display: none" Width="233px">
<asp:TextBox ID="txtResult" runat="server" AutoPostBack="True"></asp:TextBox>
<br />
<div align="center">
<asp:Button ID="OkButton" runat="server" Text="OK" />
<asp:Button ID="CancelButton" runat="server" Text="Cancel" />
</div>
</asp:Panel>
txtResult is not available within code, I tried to see if it is available in the page_load, it's not
texReults was a typo, its txtResult, I updated the ID
the intellisense does not recognize any cntr by the name txtResult
its a new web application and the panel visibility=True
maybee this wil help, above the snipet, I use ScriptManager from the AJAX Exstension
I am aware of he Asnchronius affects, partial potback, etc.
It's a managed control, you should be able to set it on the Page_Load event:
protected void Page_Load(object sender, System.EventArgs e)
{
txtResult.Text = "some text";
}
Update: Based on your update, there are a couple of things that you would need to check:
Spelling: Are you sure you're spelling the control name correctly?
Its ID in your code is "txtResults", but you're referencing it as
"txtResult".
Designer: Did you copy the aspx page or bypass VS in some way for this page? If so check the .designer file for the reference to the control: i.e. "Page1.aspx.designer.cs"
Visibility: Is the Panel control's visibility set to true? If not, then it won't render the controls that are contained within it.
Update 2: If you're doing this through scriptmanager, then I highly recommend that you read through this: http://www.wrox.com/WileyCDA/Section/Using-the-ASP-NET-AJAX-ScriptManager.id-305492.html

Cannot update an image using HttpHandler, UpdatePanel and a Timer

I'm trying in ASP.NET to use a HTTPHandler to display an image and update every 5 sec.
This httphandler simply renders the current time into a Bitmap.
In aspx side, the Image is inside a AJAX UpadtePanel, and I'm using a timer to refresh the image every 5 sec.
My problem is that :
in IE9, the image is not updated at all. My HttpHandler is requested only once.
in chrome, the image is updated but it "blinks", ie every 5s it is cleared for few secs then displayed, then cleared again etc...
For debugging purpose I have also added inside the UpdatePanel a label, filled by a random value. It is well updated in both web browsers.
Here is the code in my aspx page :
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Image ID="TheImage" alt="httpHandler" src="getImage.ashx?id=1" runat="server" />
<asp:Label ID="Label" runat="server" Font-Size="XX-Large" ></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
In my HttpHandler, I did not forget to disable caching like this :
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetNoStore();
cache.SetExpires(DateTime.MinValue);
And to prevent my IE9 web browser caching the image, I also tried to change ImageUrl each time the timer is invoked in the aspx.cs file, like following. But my HttpHandler is still called only once when the page is displayed for the first time :
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
Label.Text = ((System.Environment.TickCount / 100.0) % 360).ToString("F2");
TheImage.ImageUrl = "getImage.ashx?id=" + System.Environment.TickCount.ToString();
}
I hope my problem is well explained.
What do I do wrong?
Thanks in advance!
Some suggestions:
Add Enabled="True" to your timer.
Add the source code to your getImage.ashx to your post.
Use the asp.net tags like ImageUrl in your <asp:Image /> instead of the native html tags.
Use a div instead of an img (i.e. <asp:Panel />)
change the update mode of your UpdatePanel to Always

FileUpload in FormView inside an UpdatePanel

The Scenario:
I have an ASP.Net webpage which I intend to use for letting the user(not the real users, but content manager basically) insert and edit the records in a table using a FormView. This FormView is inside an UpdatePanel, as I'm also using cascading dropdownlists to let the user select some values.
Now, this FormView also contains 4 FileUpload controls, and as you might know that these fileupload controls require a full postback since most browsers do not let Javascript access the disk. So, this problem would have been solved by doing something like:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="InsertButton" />
<asp:PostBackTrigger ControlID="UpdateButton" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>
Edit: Forgot to add that the fileuploading takes place in the OnUpdating and OnInserting events of the SqlDataSource.
The Problem:
Since the InsertButton and the UpdateButton reside inside the Formview, I cannot directly access their ID's through markup. And MSDN says that:
Programmatically adding
PostBackTrigger controls is not
supported.
Please suggest some solution to make this work. Any insight on the matter is highly appreciated. Thanks.
P.S.- A workable solution for me was to set the UpdatePanel's PostBackTrigger as the whole FormView itself:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="FormView1" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>
But now due to a bit of change in requirements, this solution(if you call it a solution) is not acceptable.
Have you given a though about using Iframe for doing the postback ? something like:
<iframe name="uploader" id=uploader
src="uploaderSender.aspx?AllowedExtension=<%= AllowedExtension %>&StoringPath=<%= StoringPath %>&StoringFileName=<%= StoringFileName %>&OldFileName=<%= OldFileName %>&MaximumSize=<%= MaximumSize %>"
width="450" height="50" frameborder=0 scrolling=no >
</iframe>
with uploaderSender.aspx like :
<form action="UploaderReceiver.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" onchange="document.getElementById('IsFileUploading').style.visibility = 'visible'; document.forms[0].submit()"/>
<span id="IsFileUploading" style="visibility: hidden">
<asp:Image ID="Image1" runat="server" ImageUrl="~/immagini/Ajax-loader.gif" />
</span>
</form>
and UploaderReceiver.aspx like :
protected void Page_Load(object sender, EventArgs e)
{
//if there is one file to process
if (Request.Files.Count > 0)
//create the folder if it does'nt exists and returns the local path to get it
string StoringPathToBeSaved = StoringPath.GetFolderPath();
// append the name of the file to upload to the path.
StoringPathToBeSaved = StoringPathToBeSaved + StoringFileName + Extension;
Request.Files[0].SaveAs(StoringPathToBeSaved);
}
this is just bits of code just for you to figure out if you would be interested in this way of dealing with the upload, I can give you more if you want after.
see you, and good luck with your code,
Yay!! Finally got it to work!
Here's How:
Well contrary to what MSDN says, we can in fact add PostBack Triggers Programmatically. Not necessarily to the UpdatePanel, but to the ScriptManager.
After hours of playing around, here's what worked:
We are not able to access controls inside a FormView, untill the template has been rendered, so we can only add postback triggers after the formview's OnDataBound Event.
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
LinkButton lb = (LinkButton)FormView1.FindControl("UpdateButton");
ScriptManager.GetCurrent(Page).RegisterPostBackControl(lb);
}
//Similarily you can put register the Insert LinkButton as well.
}
And now, if your UpdatePanel causes ConditionalUpdate, you can do something like this to make it work:
The Markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>..
<EditItemTemplate>
...
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" OnClick="Cause_PostBack"CommandName="Update">Update</asp:LinkButton>
...
</EditItemTemplate>
..</ContentTemplate>
</asp:UpdatePanel>
CodeBehind:
//call this function as the OnClick Event Handler for the Controls you want to register as
//triggers.
protected void Cause_PostBack()
{
UpdatePanel1.Update();
}
Otherwise, if your situation allows it(as mine does), just set the UpdatePanel's UpdateMode="Always"
This is old, but was trying to solve another problem and ran into this. This wasn't my problem, but here's an alternative for anyone new who runs into this as well.
You stated your problem as:
Since the InsertButton and the UpdateButton reside inside the Formview, I cannot directly access their ID's through markup
You actually can access their ID's through markup to use as the ControlID in the PostBackTrigger. You just have to use the button's name that is created in the page html mark-up as the ControlID. You can find the name created by viewing the page source when you're viewing the page in the browser. It typically is the name of the FormView + $ + name of the button.
For example, let's say you have a FormView named "FormView1" that contains an Insert button which you gave the ID of "btnInsert" during design. If you open up your page in the browser to view it live and then view the page's source, you'll notice that the html mark-up of the button will actually be given the name "FormView1$btnInsert".
Use that name as the ControlID in your PostBackTrigger and your update panel will work.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="FormView1$btnInsert" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>

Resources