Upload Files in ASP.NET at Production Web server
Upload Files in ASP.NET at Production server
Most of the case, a developer created a code to upload the file and test it on his local machine. Program runs perfectly on local machine, but after publish that onto production server. He stuck in the file permission error as on the local machine he has the full permission whereas on the production server its not the case.
So i decided to write this tutorial for the beginners which will demonstrate how to upload a file onto webserver or production server.Step 1 :
First we need to create a folder in Server and share it with ASP.NET web server as described. Right click on folder, select Web sharing tab and select the radio button "Share this folder". One window appear, give it alias name which will be used in coding.Step 2 :
After this, open Run box and type "inetmgr". you will see that your web shared folder appears in the IIS.Step 3 :
Right click on folders property. one window will opened like below.Step 4 :
Select "Directory Security" tab then click on "Edit" button and then check "Anonymous access". And because of this setting any body can access or download that file.
Now we are ready, to create a sample application which will demonstrate that how to upload the file and use it.Step 5 :
Create ASP.NET project in Visual Studio. Create a webpage with fileupload, hyperlink and button control.
<form runat="server">
<asp:FileUpload runat="server" /><br />
<asp:HyperLink runat="server" Visible="false" Target="_blank"></asp:HyperLink><br />
<asp:Button Text="Upload" runat="server" />
</form>Step 6 :
In web.config add two keys. One for actual folder location in which we are going to upload the files and other its alias name. we can also hard code that, but its good practice to make it configurable at any time because in near future we may want to change the location.
<appSettings>
<add key="DemoAttachment" value="D:\Share\DemoShare\"></add>
<add key="DemoAttachmentVirtualPath" value="http://localhost/DemoShare/"></add>
</appSettings>
Note : In DemoAttachmentVirtualPath key, value should like "http://machinename/" + Alias folder name.Step 7 :
On click event of button, write below code:
string strPath = ConfigurationManager.AppSettings["DemoAttachment"];
uploadFile.SaveAs(strPath + System.IO.Path.GetFileName(uploadFile.FileName));
hypLink.Visible = true;
string VirtualPath = ConfigurationManager.AppSettings["DemoAttachmentVirtualPath"];
hypLink.Text = System.IO.Path.GetFileName(uploadFile.FileName);
hypLink.NavigateUrl = VirtualPath + uploadFile.FileName;
Reference: http://blog.dotnetsquare.com/?p=205