0 Replies - 1603 Views - Last Post: 13 July 2009 - 07:47 AM

#1 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1533
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Pushing File to Browser

Posted 13 July 2009 - 07:47 AM

Description: Must include the "System.IO" reference. *** NOTE *** This will not work inside of an AJAX UpdatePanel. If this code is called from a button click event, that button will need to be outside of any AJAX UpdatePanel.This snippet will push a file from the server to the browser to allow the user to download/view it.
/// 
/// Downloads (pushes) file to the client browser.  
/// **** NOTE **** Cannot be done from inside an AJAX UpdatePanel control.
/// 
/// The full file path of the file
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();
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1