过去使用Framework开发项目,最近采用.Net Core 开发,在下载文件时,习惯性的使用 response.Content返回文件流,在.net core 中遇到了两部分问题
一、首先core不再支持根路径获取的方法 HttpContext.Current.Server.MapPath(相对路径) 我搜索的时候都是关于怎么在core环境下使用current,使用自定义方法什么的,跑偏了方向。
后来发现core的根目录获取很简单,只需要 AppContext.BaseDirectory +“相对路径”就可以对服务器的文件进行操作了。
二、Freamework时可以根据a标签直接获取HttpResponseMessage的文件流然后进行下载,core返回时却是一个json对象
{ "version": { "major": 1, "minor": 1, "build": -1, "revision": -1, "majorRevision": -1, "minorRevision": -1 }, "content": { "headers": [ { "Key": "Content-Type", "Value": [ "application/xml; charset=utf-8" ] } ] }, "statusCode": 200, "reasonPhrase": "OK", "headers": [], "trailingHeaders": [], "requestMessage": null, "isSuccessStatusCode": true }
查询相关问题时,由于搜索过于局限,依然获取的是通过自定义类以及引用包,通过一些配置,使得这些就方法可以在core上运行,就像这些方法:
后来查看core的下载文件相关文章时发现,只需要return File()就可以直接通过浏览器下载了。
顿时感觉自己在用更方便的技术,考虑着如何让旧框架在新框架里面跑起来,反而忽略的新框架带来的新的方式。
旧方法:
[HttpGet] public HttpResponseMessage DownloadImportTemp() { string fileName = "模板.xlsx"; string filePath = HttpContext.Current.Server.MapPath("~/TempFile/Temp.xlsx"); FileStream stream = new FileStream(filePath, FileMode.Open); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(stream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = HttpUtility.UrlEncode(fileName) }; response.Headers.Add("Access-Control-Expose-Headers", "FileName"); response.Headers.Add("FileName", HttpUtility.UrlEncode(fileName)); return response; }
新方法:
[HttpGet("DownloadImportTemp")] public IActionResult DownloadImportTemp() { string filePath = AppContext.BaseDirectory + "/TempFile/SutdentInfoTemp.xlsx"; var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); return File(fileStream, "application/octet-stream", "学生导入模板.xlsx"); }
总结:还是菜