netcore5 jquery与vue axios 下载文件

Posted 神色自若

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了netcore5 jquery与vue axios 下载文件相关的知识,希望对你有一定的参考价值。

后端

[HttpGet("Home/Excel")]
public IActionResult Excel()
{

    string path = @"E:\\Projects\\Demos\\WebApplication1\\testmerge.xlsx";
    var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
    var fileInfo = new System.IO.FileInfo(path);
    var contentType = provider.Mappings[fileInfo.Extension];            
    var ms = System.IO.File.OpenRead(path);
    return File(ms, contentType, fileInfo.Name);
}

jquery

$.ajax({
            type: "get",
            xhrFields: {
                responseType: 'blob'
            },
            url: "/Home/Excel",
            beforeSend: function (XHR) {
                XHR.setRequestHeader('Authorization', 'Bearer 可以传token');
            }, success: function (data, successTextStatus, xhr) {                      
                var url = window.URL || window.webkitURL;
                let data_url = url.createObjectURL(data);
                let link = document.createElement('a');
                link.style.display = 'none';
                link.href = data_url;
                let min = 10000, max = 99999;//生成5位随机数
                var name=Math.floor(Math.random() * (max - min + 1) + min);
                let fileName = name+ ".xlsx";
                const contentDisposition = xhr.getResponseHeader('content-disposition');
                if (contentDisposition) {
                    fileName = window.decodeURI(contentDisposition.split('=')[2]);
                    fileName = fileName.substr(7);
                }
                link.setAttribute('download', fileName);
                document.body.appendChild(link)
                link.click();
                document.body.removeChild(link)
            }
        });

axios

 axios({
        url: '/Home/Excel',
        method:'get',
        responseType: 'blob',
        headers: {
            "Authorization": "Bearer " + getToken() //没有token删除此处headers
        },
    }).then(res=>{
        let data_url = URL.createObjectURL(res.data);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = data_url;
        let min = 10000, max = 99999;//生成5位随机数
        var name = parseInt(Math.random() * (max - min + 1) + min, 10);
        let fileName = name + ".xlsx";
        const contentDisposition = res.headers['content-disposition'];
        if (contentDisposition) {
            fileName = window.decodeURI(contentDisposition.split('=')[2]);
            fileName = fileName.substr(7);
        }
        link.setAttribute('download', fileName);
        document.body.appendChild(link)
        link.click();
        document.body.removeChild(link)
    }).catch(err=>{
    });

到这里还未完,有一部分人获取不到后端传的文件名,原因是获取不到content-disposition

前后端分离跨域是获取不到的

在Startup.cs跨域里设置下

这样写是可以的

.WithExposedHeaders("content-disposition"); 

加微信获取源码:25489181

以上是关于netcore5 jquery与vue axios 下载文件的主要内容,如果未能解决你的问题,请参考以下文章

axios的promise怎么取到里面的值

vue开发中有几种网络请求方式?用哪一种

在 vue 模板中从 axios 渲染值

Axios的介绍及使用

vue中SignalR全局封装

Vue体验(前后端交互)