【问题标题】:Get file name when downloading file下载文件时获取文件名
【发布时间】:2019-05-17 10:19:39
【问题描述】:

这是我的行动...

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

.. 在行动中。

【问题讨论】:

  • 在您的 JS 中,您应该能够访问 response 变量上的标题。访问Content-Disposition 标头,并从中解析出文件名。
  • @ChrisPratt 代码已经尝试过这个,当直接指定“Content-Disposition”时它是未定义的。
  • 嗨,有趣,这可能有一些额外的信息stackoverflow.com/posts/25715985/revisions
  • 未定义是什么意思?
  • 在 Javascript 中,undefined 是当你访问一个不存在的变量时得到的值。

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


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2011-07-08
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多