ASP.NET Core WebAPI如何获得远程文件返回文件流给前端?
一、根据网络路径把文件保存成byte[]返回给前端
项目采用的是前后端分离的模式,后端使用ASP.NET Core WebAPI方式,将文件流返回给前端。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /// <summary> /// 根据网络路径把文件保存成byte[] /// </summary> /// <param name="filePath"></param> public byte [] UrlToByte( string filePath) { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(filePath); req.Method = "GET" ; using (WebResponse wr = req.GetResponse()) { StreamReader responseStream = new StreamReader(wr.GetResponseStream(), Encoding.UTF8); int length = ( int )wr.ContentLength; byte [] bs = new byte [length]; HttpWebResponse response = wr as HttpWebResponse; Stream stream = response.GetResponseStream(); //读取到内存 MemoryStream stmMemory = new MemoryStream(); byte [] buffer1 = new byte [length]; int i; while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0) { stmMemory.Write(buffer1, 0, i); } byte [] arraryByte = stmMemory.ToArray(); stmMemory.Close(); return arraryByte; } } |
二、解决前端无法获得fileName
前端采用的是Vue技术栈,采用的是axios调用后端接口。前端无法获得fileName需要修改后端ASP.NET Core WebAPI项目中的【Startup.cs】文件。
修改ConfigureServices方法中的AddCors。
代码示例:
版权声明:本文为原创文章,版权归 [西瓜程序猿] 所有,转载请注明出处,有任何疑问请私信咨询。
原文链接:https://www.cnblogs.com/kimiliucn/p/17589873.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构