Uploading Files in ASP.net without using the FileUpload server control

Ronnie Overby picture Ronnie Overby · Feb 20, 2009 · Viewed 229.4k times · Source

How can I get an ASP.net web form (v3.5) to post a file using a plain old <input type="file" />?

I am not interested in using the ASP.net FileUpload server control.

Answer

mathieu picture mathieu · Feb 20, 2009

In your aspx :

<form id="form1" runat="server" enctype="multipart/form-data">
 <input type="file" id="myFile" name="myFile" />
 <asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>

In code behind :

protected void btnUploadClick(object sender, EventArgs e)
{
    HttpPostedFile file = Request.Files["myFile"];

    //check file was submitted
    if (file != null && file.ContentLength > 0)
    {
        string fname = Path.GetFileName(file.FileName);
        file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
    }
}