下载文件时获取文件名

时间:2019-05-16 17:44:30

标签: asp.net-core-mvc axios asp.net-core-webapi

这是我的行动...

[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");

..在动作中。

1 个答案:

答案 0 :(得分:1)

这是一个工作示例:

服务器:

[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>