天天看点

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跨域里设置下

netcore5 jquery与vue axios 下载文件

这样写是可以的

.WithExposedHeaders("content-disposition"); 

加微信获取源码:25489181