filestream
和fileinfo
只能处理本地文件路径,无法直接处理http url。以下是几种实现远程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()) { // 设置超时时间 httpclient.timeout = timespan.fromseconds(30); // 下载文件内容 var response = await httpclient.getasync(filepath); response.ensuresuccessstatuscode(); var content = await response.content.readasbytearrayasync(); // 创建返回结果 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:流式传输(节省内存)【推荐】
[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头,有些服务器需要 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, "网络请求错误"); 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
和流资源 - 超时处理:为远程请求设置合理的超时时间
- 错误处理:添加针对网络请求的特定错误处理
- 内存考虑:对于大文件,使用流式传输避免内存溢出
推荐使用方案2的流式传输,因为它内存效率更高,特别适合处理大文件。
到此这篇关于c#实现以文件流的形式返回本地文件或远程文件路径的文章就介绍到这了,更多相关c#文件流返回文件路径内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论