1. 程式人生 > 其它 >前端直接下載.txt檔案,不預覽開啟

前端直接下載.txt檔案,不預覽開啟

場景:

  有一個日誌下載的功能,之前寫了通過a標籤的下載,但是發現瀏覽器會自動預覽,並不是直接下載。

解決:

  先給出後端,這裡用的是.net:

[HttpGet]
        public IActionResult GetFile(string filepath)
        {
            var provider = new FileExtensionContentTypeProvider();
            FileInfo fileInfo = new FileInfo(filepath);
            new FileExtensionContentTypeProvider().Mappings.TryGetValue("
.txt",out var contenttype); return File(System.IO.File.ReadAllBytes(filepath), contenttype ?? "application/octet-stream", fileInfo.Name); }

  前端,這裡用的是XMLHttpRequest,用axios應該也可以。

 var request = new XMLHttpRequest();
        var url =
          "http://XXXX/api/v1/tool/systemMonitoring/download
"; url += "?"; url += "id="; url += id; request.open("GET", url); request.setRequestHeader("Content-Disposition", "attachment"); request.responseType = "blob"; //定義響應型別 request.onload = function() { var url = window.URL.createObjectURL(this
.response); var a = document.createElement("a"); document.body.appendChild(a); a.href = url; a.download = id; a.click(); }; request.send();

  主要是header中的Content-Disposition欄位,其中attachment為以檔案方式下載。disposition-parm為預設,服務端向客戶端遊覽器傳送檔案時,如果是瀏覽器支援的檔案型別,一般會預設使用瀏覽器開啟。

參考:

  https://blog.csdn.net/qq_19313497/article/details/104234723

  https://blog.csdn.net/iteye_2240/article/details/81726528

  https://www.cnblogs.com/huanyun/p/11310659.html

  https://blog.csdn.net/albert528108/article/details/96964232