streaming random filetypes from .aspx

  • Thread starter Thread starter Daniel
  • Start date Start date
D

Daniel

streaming random filetypes from .aspx

how to stream a file from inside a .aspx? e.g. so one could go
href="./foo.aspx?file=bar.mp3" or href="./foo.aspx?foo.dat" etc. preferabley
i would like all file types to open with "save as" when href clicked
 
Daniel said:
streaming random filetypes from .aspx

how to stream a file from inside a .aspx? e.g. so one could go
href="./foo.aspx?file=bar.mp3" or href="./foo.aspx?foo.dat" etc.
preferabley i would like all file types to open with "save as" when
href clicked

the aspx page is clean:
<%@ Page language="c#" Codebehind="StreamAFile.aspx.cs"
AutoEventWireup="false" Inherits="YourNamespace.StreamAFile" %>

the code behind:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;

namespace YourNamespace
{
/// <summary>
/// Generic filestreamer for ASP.NET. Receives the file with the path
relative to the site root folder.
/// </summary>
public class StreamAFile: System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
string pathFilename = (string)Request.QueryString["Filename"];

// replace "\" with "/"
pathFilename.Replace(@"\", "/");

string filename = pathFilename;
int indexLastSlash = pathFilename.LastIndexOf("/");

if(indexLastSlash>=0)
{
filename = pathFilename.Substring(indexLastSlash);
}

// put the download folder in front of it.
// chop off '..' here if you want to. You can also
// protect it in the webserver.
string completePathFilename =
Path.Combine(Application["sDownloadFilesRootFolder"].ToString(),
filename);

// test if file exists.
if(!File.Exists(completePathFilename))
{
// no. redirect
Response.Redirect("/default.aspx");
}

FileStream stream = new FileStream(completePathFilename,
FileMode.Open, FileAccess.Read);
byte[] fileContents = new byte[stream.Length];

stream.Read(fileContents, 0, (int)stream.Length);
stream.Close();

// create header
Response.ClearHeaders();
Response.AddHeader("Content-Type", "application/unknown");
Response.AddHeader("Content-Disposition", "attachment; filename=" +
filename);
Response.AddHeader("Content-Transfer-Encoding", "Binary");
Response.BinaryWrite(fileContents);
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}

FB


--
 
Back
Top