首页 > 解决方案 > 下载文件时获取文件名

问题描述

这是我的行动...

[HttpGet]
public object Download()
{
    return File("file.png", MediaTypeNames.Application.Octet, "HiMum.png");
}

在浏览器...

axios({

            url: AppPath + 'download/',
            method: 'GET',
            responseType: 'blob'
        })
        .then(response => {



            console.log(JSON.stringify(response.headers));

            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');

            link.href = url;
            link.setAttribute('download', 'file.pdf');

            link.click();

            window.URL.revokeObjectURL(url);
        });

痕迹只显示...

{"content-type":"application/octet-stream"}

如何获取文件名?我已经尝试添加...

Response.Headers.Add("Content-Disposition", $"inline; filename=HiMum.png");

..在行动中。

标签: asp.net-core-mvcaxiosasp.net-core-webapi

解决方案


这是一个工作演示:

服务器:

[HttpGet("Download")]
public object Download()
{
    return File("file.png", "application/octet-stream", "HiMum.png");
}

客户:

<script type="text/javascript">
    $(document).ready(function () {
        axios({
            url: 'download/',
            method: 'GET',
            responseType: 'blob'
        })
            .then(response => {
                console.log(JSON.stringify(response.headers));
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                var filename = "";
                var disposition = response.headers['content-disposition'];
                console.log(disposition);

                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }
                console.log(filename);
                link.setAttribute('download', filename);
                link.click();
                window.URL.revokeObjectURL(url);
            });
    });
</script>

推荐阅读