Template:ASPX Upload Files

esse quam videri
Jump to: navigation, search

Mappath

Server.Mappath will return the real physical location of a file that is in a virtual directory.

http://msdn.microsoft.com/en-us/library/ms524632%28v=vs.90%29.aspx


Special permissions need to be set on the folder that you are going to upload to. The anonymous ASP.NET account need to have write permissions to this folder. It is not recommended that folder with write permissions also have execute and should not allow directory listing.

Upload a File

http up-loader

Add executionTimeout and maxRequestLength to the web.config so that large uploads will not fail.

<xml> <configuration>

   <system.web>
       <httpRuntime
           executionTimeout="1200"
           maxRequestLength="65536"
       />
   </system.web>

</configuration> </xml>

multipart form <csharp> <form enctype="multipart/form-data" runat="server"> <tr>

 <td>Select file to upload:</td>
 <td>
 <input id="myfile" type="file" runat="server"></td>

</tr> <tr>

 <td>
 <input type=button id="btnUploadTheFile" value="Upload" 
       OnServerClick="btnUploadTheFile_Click" runat="server" />
 </td>

</tr> </form> </csharp>

Parse the multipart form and save the file msdn library. System.Web.HtmlInputFile.PostedFile Property

<csharp> void btnUploadTheFile_Click(object Source, EventArgs evArgs) {

   //Path to save file
   string strBaseLocation = "";
   
   if (null != myfile.PostedFile) 
   {
       // Get the HTTP posted file instance (to simplify the code) 
       HttpPostedFile postedfile = myfile.PostedFile; 
       
       // Get the filename 
       string filename = new System.IO.FileInfo(postedfile.FileName).Name; 
       string filesize = postedfile.ContentLength.ToString();
       try 
       {
           myfile.PostedFile.SaveAs(strBaseLocation+filename);
           txtOutput.InnerHtml = "File " + strBaseLocation + filename + " uploaded successfully";
       }
       catch (Exception e) 
       {
               txtOutput.InnerHtml = "Error saving " + strBaseLocation + filename + "

"+ e.ToString();

       }
       
       //Do some other stuff 
       //maybe  like send an email to let admin know file was uploaded
   }

} </csharp>

http://iam.colum.edu/oop/classsource/class14/up.aspx [up.aspx - source] [web.config - source]

Modifications

Unique file name

<csharp> // Get the filename

       string filename = new System.IO.FileInfo(postedfile.FileName).Name; 
       string strUniqueDate = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Ticks.ToString()  ;
       filename =  strUniqueDate + "_" + filename;

</csharp>

After you upload w file it os often wise to add the file name to a database(especially if you obfuscate the name you might want to save the original name). You may also may want to send an email notifying you that a file has been uploaded.