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.
ASP.NET FileUpload control allows us to upload files to a Web Server or storage in a Web Form. The control is a part of ASP.NET controls and can be placed to a Web Form by simply dragging and dropping from Toolbox to a WebForm. The FileUpload control was introduced in ASP.NET 2.0.
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)));     } } 
                        Here is a solution without relying on any server-side control, just like OP has described in the question.
Client side HTML code:
<form action="upload.aspx" method="post" enctype="multipart/form-data">     <input type="file" name="UploadedFile" /> </form>   Page_Load method of upload.aspx :
if(Request.Files["UploadedFile"] != null) {     HttpPostedFile MyFile = Request.Files["UploadedFile"];     //Setting location to upload files     string TargetLocation = Server.MapPath("~/Files/");     try     {         if (MyFile.ContentLength > 0)         {             //Determining file name. You can format it as you wish.             string FileName = MyFile.FileName;             //Determining file size.             int FileSize = MyFile.ContentLength;             //Creating a byte array corresponding to file size.             byte[] FileByteArray = new byte[FileSize];             //Posted file is being pushed into byte array.             MyFile.InputStream.Read(FileByteArray, 0, FileSize);             //Uploading properly formatted file to server.             MyFile.SaveAs(TargetLocation + FileName);         }     }     catch(Exception BlueScreen)     {         //Handle errors     } } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With