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

posted @ 2022-03-06 15:35  陈子白  阅读(1122)  评论(0编辑  收藏  举报