.Net Core 文件下載


過去使用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");
        }

 

總結:還是菜


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM