I was trying to upload file in asp.net web-forms using File upload control which works fine, considering article example here https://qawithexperts.com/article/asp-net/file-upload-in-aspnet-web-forms-upload-control-example/273
But what if I don't want to use file upload control of web-form, so how can I upload file in asp.net without using the fileupload server control? Basically I would like to use "<input type='file' />
"
You can do it like below
In your .aspx page
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="UploadFile" name="UploadFile" /><br/>
<asp:Button runat="server" ID="btnUpload" OnClick="UploadFile" Text="Upload File" /><br/>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</form>
In your Code behind to upload file on button click
protected void UploadFile(object sender, EventArgs e)
{
//folder path to save uploaded file
string folderPath = Server.MapPath("~/Upload/");
//Check whether Directory (Folder) exists, although we have created, if it si not created this code will check
if (!Directory.Exists(folderPath))
{
//If folder does not exists. Create it.
Directory.CreateDirectory(folderPath);
}
//get file
HttpPostedFile file = Request.Files["myFile"];
//check if file is not null
if (file != null && file.ContentLength )
{
string fname = Path.GetFileName(file.FileName);
string filePath = folderPath + fname ;
//save file
file.SaveAs(filePath );
//once file is uploaded show message to user in label control
Label1.Text = fname + " has been uploaded.";
}
}
That's it.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly