Home > Backend Development > C++ > How to Download and Stream Files from a Remote URL in ASP.NET?

How to Download and Stream Files from a Remote URL in ASP.NET?

Mary-Kate Olsen
Release: 2025-01-06 08:26:43
Original
768 people have browsed it

How to Download and Stream Files from a Remote URL in ASP.NET?

Download/Stream file from URL - asp.net

In certain scenarios, it may be necessary to stream or download a file from a remote URL and trigger a "Save As" prompt in the browser. However, when the file is located in a virtually mapped directory, accessing its actual location using Server.MapPath can be challenging.

Instead, you can leverage the power of HttpWebRequest to achieve this functionality. Here's an example that allows you to pass a web URL:

using System.IO;
using System.Net;

namespace FileDownloader
{
    public static class FileDownloader
    {
        public static void DownloadFile(string url, string fileName)
        {
            // Create a stream for the file
            Stream stream = null;

            // Configure streaming chunk size
            int bytesToRead = 10000;

            // Buffer to read bytes in specified chunk size
            byte[] buffer = new Byte[bytesToRead];

            // Initialize response
            HttpWebResponse fileResp = null;

            try
            {
                // Create a WebRequest to get the file
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);

                // Get a response for this request
                fileResp = (HttpWebResponse)fileReq.GetResponse();

                // Get the Stream returned from the response
                stream = fileResp.GetResponseStream();

                // Prepare the response to the client
                HttpResponse resp = HttpContext.Current.Response;

                // Set response type and add headers
                resp.ContentType = MediaTypeNames.Application.Octet;
                resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

                int length;
                do
                {
                    // Verify client connection
                    if (resp.IsClientConnected)
                    {
                        // Read data into the buffer
                        length = stream.Read(buffer, 0, bytesToRead);

                        // Write data to the response's output stream
                        resp.OutputStream.Write(buffer, 0, length);

                        // Flush the data
                        resp.Flush();

                        // Clear the buffer
                        buffer = new Byte[bytesToRead];
                    }
                    else
                    {
                        // Cancel download if client disconnects
                        length = -1;
                    }
                } while (length > 0); // Repeat until no data remains
            }
            finally
            {
                // Close the input stream
                if (stream != null)
                {
                    stream.Close();
                }

                // Dispose the response
                if (fileResp != null)
                {
                    fileResp.Close();
                }
            }
        }
    }
}
Copy after login

By using this approach, you can stream files from remote URLs and allow users to save them locally with a dynamically generated file name.

The above is the detailed content of How to Download and Stream Files from a Remote 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