首頁 > 後端開發 > C++ > 如何在 ASP.NET 中從遠端 URL 串流或下載檔案?

如何在 ASP.NET 中從遠端 URL 串流或下載檔案?

Linda Hamilton
發布: 2025-01-06 08:09:41
原創
769 人瀏覽過

How to Stream or Download Files from Remote URLs in ASP.NET?

從ASP.NET 中的遠端URL 串流或下載檔案

問題:

問題:

問題:

問題:
    //Create a stream for the file
    Stream stream = null;

    //This controls how many bytes to read at a time and send to the client
    int bytesToRead = 10000;

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

    // The number of bytes read
    try
    {
        //Create a WebRequest to get the file
        HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);

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

        if (fileReq.ContentLength > 0)
            fileResp.ContentLength = fileReq.ContentLength;

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

        // prepare the response to the client. resp is the client Response
        var resp = HttpContext.Current.Response;

        //Indicate the type of data being sent
        resp.ContentType = MediaTypeNames.Application.Octet;

        //Name the file 
        resp.AddHeader("Content-Disposition", "attachment; filename=\"\"" + fileName + "\"\"");
        resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

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

                // and write it out 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 the download if client has disconnected
                length = -1;
            }
        } while (length > 0); //Repeat until no data is read
    }
    finally
    {
        if (stream != null)
        {
            //Close the input stream
            stream.Close();
        }
    }
登入後複製
您需要從遠端URL 串流或下載檔案並將其顯示為瀏覽器中的另存為對話方塊。然而,該檔案的目錄是虛擬的,無法透過 Server.MapPath 等傳統方法存取它。 解決方案:利用 HttpWebRequest 從 URL 和流中擷取檔案它傳回給客戶端。這種方法可讓您處理只能透過 URL 存取的檔案。 下面是一個程式碼範例:

以上是如何在 ASP.NET 中從遠端 URL 串流或下載檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板