The problem that I am having is getting the file information from an without the use of a <input type=file> into a code behind method. The file always returns as null in the code behind when I try to get the information using <form> and I believe this is because it is never actually being sent to the server. Request.Files
Is there anyway to get the file information sent to the server without the use of a ? <form>
Here is the html I am using
<input type="file" id="upload_file" name="upload_file" runat="server" accept="image/*" onchange="copyFile()" />
And this is the code behind
HttpPostedFile file = Request.Files["upload_file"];
if (file != null && file.ContentLength > 0)
{
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
}
I cannot use a due to the way the webpage is being set up, it causes some horrible formatting issues in only IE (even IE9) that I cannot fix in css. Also, I am using <form> rather than the <input type=file> so that I can have access to the <asp:FileUpload>onchange event.
Edit!
On a masterpage buried within the website is a form which already has the runat ="server" added to it. Sorry for not mentioning this earlier, I just found out when trying to add a runat="server" to the new form I am trying to create
Any help would be greatly appreciated! Thank you!
EDIT!
Final Code
Thank you to both @bkwint and @TrizZz, without your help, I would still be trying to figure this out.
The html part
<asp:FileUpload id="upload_file" runat="server" OnLoad="upload_file_OnLoad" />
the code behind to add in the onchange to the asp:FileUpload
protected void upload_file_OnLoad(object sender, EventArgs e)
{
((System.Web.UI.WebControls.FileUpload)sender).Attributes.Add("onchange", "copyFile();");
}
and the code behind to save the file
if (Request.Files.Count > 0)
{
if (Request.Files[0].FileName.Length > 0)
{
Request.Files[0].SaveAs("~/App_Data/" + Request.Files[0].FileName);
}
}
The javascript that allows me to use the form in the master page for the submit with the onchange that was added to the asp:FileUpload. The id 'aspnetForm' is the form that is in the master page.
document.getElementById('aspnetForm').submit();
From what I have learned through some more research is that what was probably causing the css to be unhappy and the form to not submit properly was because nested forms are bad. Since there was a form I had no idea about on the master page, when I added another form, the web page just kind of ignored the one I added. By calling the submit on the master page, the file that is uploaded is correctly pushed to the server.
Thank you again to everyone who replied/commented and helped!
NOTE
This may not work in IE depending on how you set it up. IE does not like it when you try to submit a form directly from the fileupload.
form.