前端直接下載.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


免責聲明!

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



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