Eclipsed4utoo's Blog
Not Your Ordinary Programmer

Posts Tagged ‘ASP.Net’

ASP.Net – Pushing File to Browser

Wed ,05/08/2009

Here is a short snippet that will push/serve a file from the server to the browser for download.

****** NOTE *******
This will not work inside of an AJAX UpdatePanel.  If the code is called from a button click event, that button will need to be outside of any AJAX UpdatePanel.

protected void DownloadFile(string fullFilePath)
{
      // Gets the File Name
      string fileName = fullFilePath.Substring(fullFilePath.LastIndexOf('\\') + 1);
      byte[] buffer;

      using (FileStream fileStream = new FileStream(fullFilePath, FileMode.Open))
      {
           int fileSize = (int)fileStream.Length;

           buffer = new byte[fileSize];

           // Read file into buffer
           fileStream.Read(buffer, 0, (int)fileSize);
      }

      Response.Clear();

      Response.Buffer = true;
      Response.BufferOutput = true;
      Response.ContentType = "application/x-download";
      Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
      Response.CacheControl = "public";
      // writes buffer to OutputStream
      Response.OutputStream.Write(buffer, 0, buffer.Length);
      Response.End();
}

ASP.Net – Uploading File To Server

Tue ,04/08/2009

Here is a small snippet of code that will allow visitors to your website to upload files to your server.

This code will open an OpenFileDialog box to allow the user to select a file.

<asp:TableCell>
     Select File:
     <input id="uplTheFile" type="file" runat="server" style="width: 476px; height: 26px" />
</asp:TableCell>

This code will add a button to the form to upload the file.

<asp:TableCell>
     <asp:Button ID="cmdUploadFile" value="Upload" runat="server" Text="Upload" OnClick="cmdUploadFile_Click" />
</asp:TableCell>

cmdUploadFile_Click Event

protected void cmdUploadFile_Click(object sender, EventArgs e)
{
     string strFileNameOnServer = uplTheFile.PostedFile.FileName;
     string appDataPath = HttpContext.Current.Server.MapPath("~/App_Data");

     if (string.IsNullOrEmpty(strFileNameOnServer))
     {
           lblInformation.Text = "Error - a file name must be specified.";
           return;
     }

     if (uplTheFile.PostedFile != null)
     {
          try
          {
               uplTheFile.PostedFile.SaveAs(appDataPath + "\\" + strFileNameOnServer);
          }
          catch (Exception ex)
          {
               lblInformation.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>.  " + ex.Message;
          }
      }
}

This will upload the file into the App_Data folder of the website.

ASP.Net – Calling JavaScript from Code Behind

Fri ,31/07/2009

.Net gives us the ability to call javascript code from the code behind. This means that you don’t have to write the javascript code in the “Source” of the aspx page.

Just for an example, let’s say that you have a button on a form that just want to popup an alert that says “HEY” when it is clicked.

protected void btnHey_Click(object sender, EventArgs e)
{
     StringBuilder sb = new StringBuilder();
     sb.Append("<script language='javascript'>alert('HEY');</script>");

     // if the script is not already registered
     if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "HeyPopup"))
          ClientScript.RegisterClientScriptBlock(Page.GetType(), "HeyPopup", sb.ToString());
}

To run a method that is already defined in the .aspx page, you would use similar code, but with one difference:

// javascript method
<script language="javascript" type="text/javascript">
    function ShowMessage(myMessage){
        alert(myMessage);
    }
</script>

// C# code
protected void btnHey_Click(object sender, EventArgs e)
{
   StringBuilder sb = new StringBuilder();
   sb.Append("ShowMessage('hey');");

   // if the script is not already registered
   if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "HeyPopup"))
       // notice that I added the boolean value as the last parameter
       ClientScript.RegisterClientScriptBlock(Page.GetType(), "HeyPopup", sb.ToString(), true);

And it’s that simple.