How to upload file in ASP.NET without using asp file upload control?


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' />"


Asked by:- neena
0
: 4207 At:- 4/18/2020 8:37:22 AM
ASP.NET c# upload file without fileupload control







1 Answers
profileImage Answered by:- vikas_jk

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.

1
At:- 4/18/2020 9:20:01 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use