Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 820
Ronnie Overby Avatar asked Feb 20 '09 13:02

Ronnie Overby


People also ask

What is FileUpload control in asp net?

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.


2 Answers

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)));     } } 
like image 183
mathieu Avatar answered Sep 24 '22 06:09

mathieu


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     } } 
like image 32
Aycan Yaşıt Avatar answered Sep 21 '22 06:09

Aycan Yaşıt