
Question:
How can a file be streamed from a URL and prompted to save in the browser?
Background:
In this scenario, a file is stored in a virtually mapped directory, making it inaccessible via Server.MapPath. The goal is to stream the file while passing a web URL instead of a server file path.
Solution:
To overcome this issue, HttpWebRequest can be utilized to retrieve the file from the URL and stream it back to the client.
// Create stream for the file
Stream stream = null;
// Chunk size for reading bytes
int bytesToRead = 10000;
// Buffer for reading bytes
byte[] buffer = new Byte[bytesToRead];
try
{
// HTTP request to get the file
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);
// HTTP response for the request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
// Get response stream
stream = fileResp.GetResponseStream();
// Client response object
var resp = HttpContext.Current.Response;
// Indicate data type
resp.ContentType = "application/octet-stream";
// File name
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// File size
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Client connected?
if (resp.IsClientConnected)
{
// Read data into buffer
length = stream.Read(buffer, 0, bytesToRead);
// Write data to output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush data
resp.Flush();
// Clear buffer
buffer = new Byte[bytesToRead];
}
else
{
// Cancel if client disconnected
length = -1;
}
} while (length > 0);
}
finally
{
// Close input stream
if (stream != null)
stream.Close();
}The above is the detailed content of How to Stream and Prompt Download of a File from a URL in ASP.NET?. For more information, please follow other related articles on the PHP Chinese website!