C#實(shí)現(xiàn)以文件流的形式返回本地文件或遠(yuǎn)程文件路徑
FileStream和FileInfo只能處理本地文件路徑,無(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è)谑褂肳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í)間
這篇文章主要為大家詳細(xì)介紹了C#如何使用Sleep(Int32)方法實(shí)現(xiàn)動(dòng)態(tài)顯示時(shí)間,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下2024-01-01
C#高性能動(dòng)態(tài)獲取對(duì)象屬性值的步驟
這篇文章主要介紹了C#高性能動(dòng)態(tài)獲取對(duì)象屬性值的步驟,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2020-12-12
Unity實(shí)現(xiàn)簡(jiǎn)單虛擬搖桿
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)簡(jiǎn)單虛擬搖桿,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
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)容
從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

