FileUpload.hasFile is always False
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);
}
}