webapi返回execl文件前端下载

api代码

public HttpResponseMessage GetFile()
        {
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                var _fileName = "123.xlsx";
                //获取文件的绝对路径
                string absolutePath = System.Web.Hosting.HostingEnvironment.MapPath("/file/a.xlsx");
                System.IO.FileStream fs = new System.IO.FileStream(absolutePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                httpResponseMessage.Content = new StreamContent(fs);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                if (!string.IsNullOrEmpty(_fileName))
                {
                    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = HttpUtility.UrlEncode(_fileName, Encoding.UTF8),
                    };
                }
                return httpResponseMessage;
            }
            catch
            {
                httpResponseMessage.Dispose();
                throw;
            }
        }

 

前端代码

<script>
        function download() {
            $.ajax({
                url: 'http://localhost:50099/api/Home/GetFile',
                method: 'get',
                contentType:'application/x-www-form-urlencoded',
                xhr:function(){
                    var xhr = new XMLHttpRequest();
                    xhr.responseType = 'arraybuffer';
                    return xhr;
                },
            }).done((data)=>{
                var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"});
                console.log(blob);
                let URL = window.URL || window.webkitURL;
                let objectUrl = URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.href = objectUrl; // 文件流生成的url
                a.download = "456.xlsx"; // 文件名
                document.body.appendChild(a);
                a.click();
                a.remove();
            })   
        }
    </script>

 

posted @ 2021-04-29 14:46  怀星  阅读(311)  评论(0)    收藏  举报