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

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

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

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

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

[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下載遠(yuǎn)程文件
            using (var httpClient = new HttpClient())
            {
                // 設(shè)置超時(shí)時(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:添加緩存和錯(cuò)誤處理

[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("遠(yuǎn)程文件未找到")
                    };
                }
                
                // 獲取文件名(從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ò)請(qǐng)求錯(cuò)誤");
        return new HttpResponseMessage(HttpStatusCode.BadGateway);
    }
    catch (TaskCanceledException timeoutEx)
    {
        logger.Error(timeoutEx, "請(qǐng)求超時(shí)");
        return new HttpResponseMessage(HttpStatusCode.RequestTimeout);
    }
    catch (Exception ex)
    {
        logger.Error(ex, ex.Message);
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
}

重要注意事項(xiàng)

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

推薦使用方案2的流式傳輸,因?yàn)樗鼉?nèi)存效率更高,特別適合處理大文件。

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

相關(guān)文章

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

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

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

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

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

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

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

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

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

    Unity實(shí)現(xiàn)簡(jiǎn)單虛擬搖桿

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

    c#通過(guò)xpath讀取xml示例

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

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

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

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

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

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

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

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

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

最新評(píng)論

盐池县| 桃园市| 平凉市| 临海市| 广德县| 丰原市| 贵溪市| 德格县| 墨江| 金乡县| 台山市| 莎车县| 若羌县| 壶关县| 泰兴市| 天门市| 漯河市| 兴山县| 紫阳县| 墨脱县| 谢通门县| 海宁市| 砀山县| 遂昌县| 文水县| 抚顺县| 任丘市| 广灵县| 乌什县| 隆安县| 南康市| 新疆| 布拖县| 清丰县| 巢湖市| 天祝| 崇州市| 永修县| 抚宁县| 淮滨县| 恩施市|