ホームページ >バックエンド開発 >C++ >ASP.NET でリモート URL からファイルをダウンロードしてストリーミングする方法は?

ASP.NET でリモート URL からファイルをダウンロードしてストリーミングする方法は?

Mary-Kate Olsen
Mary-Kate Olsenオリジナル
2025-01-06 08:26:43822ブラウズ

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

URL からのファイルのダウンロード/ストリーミング - asp.net

特定のシナリオでは、リモート URL からファイルをストリーミングまたはダウンロードし、「ブラウザで「名前を付けて保存」というプロンプトが表示されます。ただし、ファイルが仮想的にマップされたディレクトリに配置されている場合、Server.MapPath を使用して実際の場所にアクセスするのは困難な場合があります。

代わりに、HttpWebRequest の機能を利用してこの機能を実現できます。 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();
                }
            }
        }
    }
}

このアプローチを使用すると、リモート URL からファイルをストリーミングし、ユーザーが動的に生成されたファイル名でローカルに保存できるようになります。

以上がASP.NET でリモート URL からファイルをダウンロードしてストリーミングする方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。