Thursday 20 March 2014

upload file in asp.net

With the FileUpload control it’s very easy to perform the operation of uploading the file in sever.But remember that there is some security concern on that folder location. 
You need to provide read and write permission to that folder where you are saving the file in server.

@ASP.Net control for file upload controller;

Code sample of HTML Input control
<tr>
     <td width="20%" align="right" valign="middle" style="height: 25px">
           <span class="Required">*</span>Image :
 </td>
  <td align="left" valign="middle" style="height: 25px">
    <input type="file" id="inpImage" runat="server" />
</td>
  </tr>


Code sample of ASP.Net File control
  <tr>
     <td width="20%" align="right" valign="middle" style="height: 25px">
       <span class="Required">*</span>Image :
   </td>
     <td align="left" valign="middle" style="height: 25px">
                       <asp:FileUpload id="FileUploadControl" runat="server" />
              </td>
</tr>


@C# Code for upload the control; It will fire on button click event


protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        lblInsertMessage.Visible = false;
        string ImageUrl = string.Empty;
        if (inpImage.PostedFile != null && inpImage.PostedFile.ContentLength != 0)
        {
            string UniqueId = GetUniqueKey(10);
            string strFilename = inpImage.PostedFile.FileName.Substring(inpImage.PostedFile.FileName.LastIndexOf("\\") + 1);
            inpImage.PostedFile.SaveAs(Server.MapPath("~/UploadImage/") + Session.SessionID + "_Hotel_" + strFilename);  // Given the uniqueidentifier to each file
            ImageUrl = Session.SessionID + "_Hotel_" + strFilename; // this is string which will save to database and used to get the file load again
        }
        else
        {
            ImageUrl = string.Empty;
        }
}

No comments:

Post a Comment