Using "<input type =" file ".... /"> "instead of asp: FileUpload
I am modifying an existing ASP.NET project. The original author mistakenly tried to create a stylized asp: FileUpload, setting its visibility to hidden and simply creating two custom search and save buttons.
For security reasons, IE does not allow this. My strategy is to use input tags with type = "file" instead, like this example . Therefore, if I configure the input as <input type="file" ID="inputFile" />, how do I get / save the file in my code behind inputFile.SaveAs("someFile.txt");,? Also (in the code behind) can I do something like, inputFile.HasFileor is there some other analogue of this?
As recommended, I'm trying to do 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>
So, you can create a random file name for future download based GUIDon the CodeBehindASPX page 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);
}
}
To Request.Files["uploadFieldNameFromHTML"]set the identifier in the HTML code here:
<input type='file' id='...' />
In addition, do not forget to define runat="server"in the main form on the ASPX page, it is better to install it in the main form and do not forget about the parameter enctype="multipart/form-data" <form>:
<body>
<form enctype="multipart/form-data" id="form1" runat="server">
<input type='file' id='uploadFieldNameFromHTML' />
...
if(fileUrunResim.HasFile)
fileUrunResim.SaveAs(MapPath("~/Images/" + fileUrunResim.FileName));
**if you unique filename,**
string extension = Path.GetExtension(fileUrunResim.FileName);
string fileName = Guid.NewGuid().ToString().Substring(0, 25) + extension ;
if(fileUrunResim.HasFile)
fileUrunResim.SaveAs(MapPath("~/Images/" + filename ));
, runat = "server" .
, , . :
Uploading files to ASP.net without using the FileUpload server element
Hope for this help
Hooray!