- A+
所属分类:.NET技术
一、根据网络路径把文件保存成byte[]返回给前端
项目采用的是前后端分离的模式,后端使用ASP.NET Core WebAPI方式,将文件流返回给前端。
/// <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。
代码示例:
.WithExposedHeaders("Content-Disposition");//应前端要求暴露Content-Disposition