Forwarding WebResponse File To Web Browser

  • Thread starter Thread starter Jeff G.
  • Start date Start date
J

Jeff G.

Hello everyone,

I have read through the newsgroups (thank God for 'em!) extensively looking
for an example of how to pass a file (PDF) from a webresponse stream down to
a web client. Here's the scenario - when the web browser requests a file,
the IIS Server1 has to go back to Server2 to make a request for the file.
Server2 then responds the file back to Server1 and Server1 should be able to
just forward the file down to the web browser. Can someone give me some of
the nitty gritty of how I can properly form the final response from Server1
down to the web browser? I have no trouble getting the response back from
Server2 to Server1. I just now need to format the response properly to get
the file down to the web browser. Many thanks in advance for your help

FYI, all I am looking for is how to format the response. If you want to
give me a code sample, you can assume that I have the WebResponse and start
from there. Again...thanks!!

Jeff G.
 
One other thing - I am trying not to have to write this file to disk before
I send it down. Would like to forward it on down directly out of memory.
Thanks again for reading and responding!

Jeff G.
 
Ok...I have worked up something after several days of work...hope this helps
someone else. What I found was that I needed to use a Binary Reader to
handle writing the file to the OutputStream. Check it out.

// Put the webResponse in a stream
Stream stream = webResponse.GetResponseStream();

// Setup the content disposition to ensure that the file "Open or Save"
dialog is popped in the browser
string contentDisposition =
webResponse.Headers["Content-Disposition"].ToString();
contentDisposition = contentDisposition.Replace("inline", "attachment");


try
{
// Change the Headers
System.Web.HttpContext.Current.Response.ClearHeaders();
// Write the type of file we are downloading
System.Web.HttpContext.Current.Response.ContentType =
pdmResponse.Headers["Content-Type"].ToString(); //"application/pdf";
// Assign a file name and the way that the file will be downloaded
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
contentDisposition);


// Since we know we are getting a Binary File we need a BinaryReader to
take in the stream
BinaryReader binaryReader = new BinaryReader(stream);
// Read the stream via the BinaryReader into a byte buffer
byte[] buffer = binaryReader.ReadBytes((int)webResponse.ContentLength);
// Write that buffer into the Output stream
System.Web.HttpContext.Current.Response.OutputStream.Write(buffer, 0,
(int)webResponse.ContentLength);

// Make the flush call send down the file.
System.Web.HttpContext.Current.Response.Flush();

}
catch(Exception e)
{
throw new ApplicationException("Failed to put file into output stream.",
e);
}



Jeff G.
 
Back
Top