最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#實現(xiàn)以文件流的形式返回本地文件或遠程文件路徑

 更新時間:2025年08月21日 15:49:43   作者:VipSoft  
FileStream和FileInfo只能處理本地文件路徑,無法直接處理HTTP URL,所以下面小編就來和大家詳細介紹一下C#如何實現(xiàn)以文件流的形式返回本地文件或遠程文件路徑吧

FileStreamFileInfo只能處理本地文件路徑,無法直接處理HTTP URL。以下是幾種實現(xiàn)遠程PDF返回給前端的解決方案:

方案1:使用HttpClient下載遠程文件(推薦)

[HttpGet]
public async Task<HttpResponseMessage> GetReportFile()
{  
    try
    {
        string orderNo = HttpContext.Current.Request.QueryString["orderNo"];
        string filePath = "D:\\1.pdf";
        
        if(!string.IsNullOrEmpty(orderNo))
        {            
            filePath = "http://www.a.com/1.pdf";
            
            // 使用HttpClient下載遠程文件
            using (var httpClient = new HttpClient())
            {
                // 設(shè)置超時時間
                httpClient.Timeout = TimeSpan.FromSeconds(30);
                
                // 下載文件內(nèi)容
                var response = await httpClient.GetAsync(filePath);
                response.EnsureSuccessStatusCode();
                
                var content = await response.Content.ReadAsByteArrayAsync();
                
                // 創(chuàng)建返回結(jié)果
                var result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new ByteArrayContent(content);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
                {
                    FileName = "document.pdf"
                };
                
                return result;
            }
        }
        else
        {
            // 處理本地文件
            FileInfo foundFileInfo = new FileInfo(filePath);
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(fs);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
            {
                FileName = foundFileInfo.Name
            };
            
            return result;
        }
    }
    catch (Exception ex)
    {
        logger.Error(ex, ex.Message);
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }
}

方案2:流式傳輸(節(jié)省內(nèi)存)【推薦】

[HttpGet]
public async Task<HttpResponseMessage> GetReportFile()
{  
    try
    {
        string orderNo = HttpContext.Current.Request.QueryString["orderNo"];
        string filePath = "D:\\1.pdf";
        
        if(!string.IsNullOrEmpty(orderNo))
        {            
            filePath = "http://www.a.com/1.pdf";
            
            using (var httpClient = new HttpClient())
            {
                httpClient.Timeout = TimeSpan.FromSeconds(30);
                
                // 流式下載
                var response = await httpClient.GetAsync(filePath, HttpCompletionOption.ResponseHeadersRead);
                response.EnsureSuccessStatusCode();
                
                var stream = await response.Content.ReadAsStreamAsync();
                
                var result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
                {
                    FileName = "document.pdf"
                };
                
                return result;
            }
        }
        else
        {
            // 本地文件處理...
        }
    }
    catch (Exception ex)
    {
        logger.Error(ex, ex.Message);
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }
}

方案3:添加緩存和錯誤處理

[HttpGet]
public async Task<HttpResponseMessage> GetReportFile()
{  
    try
    {
        string orderNo = HttpContext.Current.Request.QueryString["orderNo"];
        string filePath = "D:\\1.pdf";
        
        if(!string.IsNullOrEmpty(orderNo))
        {            
            filePath = "http://www.a.com/1.pdf";
            
            using (var httpClient = new HttpClient())
            {
                // 添加User-Agent頭,有些服務(wù)器需要
                httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
                httpClient.Timeout = TimeSpan.FromSeconds(30);
                
                // 先獲取頭部信息檢查文件是否存在
                var headResponse = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, filePath));
                
                if (!headResponse.IsSuccessStatusCode)
                {
                    return new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent("遠程文件未找到")
                    };
                }
                
                // 獲取文件名(從Content-Disposition或URL中提取)
                string fileName = "document.pdf";
                if (headResponse.Content.Headers.ContentDisposition != null)
                {
                    fileName = headResponse.Content.Headers.ContentDisposition.FileName ?? fileName;
                }
                
                // 下載文件
                var getResponse = await httpClient.GetAsync(filePath, HttpCompletionOption.ResponseHeadersRead);
                getResponse.EnsureSuccessStatusCode();
                
                var result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(await getResponse.Content.ReadAsStreamAsync());
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
                {
                    FileName = fileName
                };
                
                // 添加緩存頭(可選)
                result.Headers.CacheControl = new CacheControlHeaderValue()
                {
                    MaxAge = TimeSpan.FromHours(1)
                };
                
                return result;
            }
        }
        else
        {
            // 本地文件處理...
        }
    }
    catch (HttpRequestException httpEx)
    {
        logger.Error(httpEx, "網(wǎng)絡(luò)請求錯誤");
        return new HttpResponseMessage(HttpStatusCode.BadGateway);
    }
    catch (TaskCanceledException timeoutEx)
    {
        logger.Error(timeoutEx, "請求超時");
        return new HttpResponseMessage(HttpStatusCode.RequestTimeout);
    }
    catch (Exception ex)
    {
        logger.Error(ex, ex.Message);
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
}

重要注意事項

  • 異步方法:將方法改為async Task<HttpResponseMessage>以支持異步操作
  • 資源釋放:確保正確釋放HttpClient和流資源
  • 超時處理:為遠程請求設(shè)置合理的超時時間
  • 錯誤處理:添加針對網(wǎng)絡(luò)請求的特定錯誤處理
  • 內(nèi)存考慮:對于大文件,使用流式傳輸避免內(nèi)存溢出

推薦使用方案2的流式傳輸,因為它內(nèi)存效率更高,特別適合處理大文件。

到此這篇關(guān)于C#實現(xiàn)以文件流的形式返回本地文件或遠程文件路徑的文章就介紹到這了,更多相關(guān)C#文件流返回文件路徑內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#實現(xiàn)拆分合并Word表格中的單元格

    C#實現(xiàn)拆分合并Word表格中的單元格

    我們在使用Word制作表格時,由于表格較為復(fù)雜,只是簡單的插入行、列并不能滿足我們的需要。要做一個完整的表格,很多時候需要將單元格進行拆分或者合并。本文將詳細為您介紹在Word表格中拆分或合并單元格的思路及方法,希望對大家有所幫助
    2022-12-12
  • C#使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間

    C#使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間

    這篇文章主要為大家詳細介紹了C#如何使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考下
    2024-01-01
  • 使用C#實現(xiàn)MD5加密的方法詳解

    使用C#實現(xiàn)MD5加密的方法詳解

    在軟件開發(fā)中,加密是保護數(shù)據(jù)安全的重要手段之一,MD5(Message Digest Algorithm 5)是一種常用的哈希算法,用于生成數(shù)據(jù)的摘要或哈希值,本文介紹了如何使用C#語言實現(xiàn)MD5加密的方法,涵蓋了基本的使用方式和擴展方法封裝,需要的朋友可以參考下
    2024-08-08
  • C#高性能動態(tài)獲取對象屬性值的步驟

    C#高性能動態(tài)獲取對象屬性值的步驟

    這篇文章主要介紹了C#高性能動態(tài)獲取對象屬性值的步驟,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2020-12-12
  • Unity實現(xiàn)簡單虛擬搖桿

    Unity實現(xiàn)簡單虛擬搖桿

    這篇文章主要為大家詳細介紹了Unity實現(xiàn)簡單虛擬搖桿,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • c#通過xpath讀取xml示例

    c#通過xpath讀取xml示例

    這篇文章主要介紹了c#通過xpath讀取xml示例,需要的朋友可以參考下
    2014-04-04
  • 詳解C#App.config和Web.config加密

    詳解C#App.config和Web.config加密

    本篇文章給大家分享了C#App.config和Web.config加密的相關(guān)知識點以及具體代碼步驟,有興趣的朋友參考學(xué)習下。
    2018-05-05
  • C#實現(xiàn)簡易多人聊天室

    C#實現(xiàn)簡易多人聊天室

    這篇文章主要為大家詳細介紹了C#實現(xiàn)簡易多人聊天室,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • C# Datatable篩選過濾的四種方法實現(xiàn)

    C# Datatable篩選過濾的四種方法實現(xiàn)

    本文主要介紹了C# Datatable篩選過濾的四種方法實現(xiàn),包括Select、LINQ、DataView、動態(tài)條件,各方法在排序、性能及適用場景上有不同特點,感興趣的可以了解一下
    2025-06-06
  • c# 從IE瀏覽器獲取當前頁面的內(nèi)容

    c# 從IE瀏覽器獲取當前頁面的內(nèi)容

    從IE瀏覽器獲取當前頁面內(nèi)容可能有多種方式,今天我所介紹的是其中一種方法?;驹恚寒斒髽它c擊當前IE頁面時,獲取鼠標的坐標位置,根據(jù)鼠標位置獲取當前頁面的句柄,然后根據(jù)句柄,調(diào)用win32的東西進而獲取頁面內(nèi)容。感興趣的朋友可以參考下本文
    2021-06-06

最新評論

周至县| 赣榆县| 延庆县| 攀枝花市| 铁岭市| 信宜市| 滦南县| 南昌市| 乐陵市| 衡阳市| 东阳市| 嘉荫县| 依安县| 建宁县| 金溪县| 长治县| 商河县| 邯郸市| 天全县| 宝应县| 新绛县| 永寿县| 遵义市| 辉南县| 兴海县| 新泰市| 平谷区| 桑日县| 三门县| 当雄县| 珲春市| 竹山县| 金阳县| 博客| 自贡市| 枣强县| 繁昌县| 新竹市| 特克斯县| 淮北市| 西峡县|