Using "<input type="file" .... />" instead of asp:FileUpload
asp.net, c#, file-upload, html
Solution
So, you can generate a random file name for the a future upload, based on the `GUID` at the `CodeBehind` of ASPX page:
HttpPostedFile filePosted = Request.Files["uploadFieldNameFromHTML"];
if (filePosted != null && filePosted.ContentLength > 0)
{
string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName);
string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication);
// generating a random guid for a new file at server for the uploaded file
string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
// getting a valid server path to save
string filePath = System.IO.Path.Combine(Server.MapPath("uploads"), newFile);
if (fileNameApplication != String.Empty)
{
filePosted.SaveAs(filePath);
}
}
For `Request.Files["uploadFieldNameFromHTML"]` set the ID in HTML code here:
<input type='file' id='...' />
Also, don't forget to define `runat="server"` at the main form in ASPX page, it's better to set it at the main form and don't forget about `enctype="multipart/form-data"` parameter of the `<form>`:
<body>
<form enctype="multipart/form-data" id="form1" runat="server">
<input type='file' id='uploadFieldNameFromHTML' />
...
Problem
I'm modifying an existing ASP.NET project. The original author erroneously tried to create a styled asp:FileUpload by setting its visibility to hidden and just creating two custom styled browse and save buttons. For security reason, IE does not permit this. My strategy is to instead try to use input tags with type="file", like this example. So if I set up the input like `<input type="file" ID="inputFile" />` how do I access/save the file in my code behind, `inputFile.SaveAs("someFile.txt");`? Also (in code behind) can I do something like `inputFile.HasFile` or is there some other analog of this? As per recommendations I'm trying something like the following: ``` <td> Enabled: <asp:CheckBox ID="CheckBox2" runat="server" /> <div id="testFileUploader">> <input type="file" id="browserHidden" runat="server" /> <div id="browserVisible"><input type="text" id="fileField" /></div> </div> </td> ```