Home > Backend Development > C++ > How to Stream and Prompt Download of a File from a URL in ASP.NET?

How to Stream and Prompt Download of a File from a URL in ASP.NET?

Patricia Arquette
Release: 2025-01-06 08:06:41
Original
219 people have browsed it

How to Stream and Prompt Download of a File from a URL in ASP.NET?

Downloading and Streaming Files from URLs in ASP.NET

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template