首页 > 解决方案 > 获取 blob 未处理文件名中带有 # 字符的 url

问题描述

我使用这个 javascript 代码从后端下载二进制文件。

        // This is only a helper class for Ajax request
        new SimpleAjaxRequest().safeRequest("mainpage/downloaddocument.php",
        {
            questionnaireid: questionnaire.id
        }, true, false, (response) =>
        {
            fetch(response.data.url) // This url is like "xxxx.com/download/filename #1.xlsx"
                .then(resp => resp.blob())
                .then(blob =>
                {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    // the filename you want
                    a.download = response.data.name;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                })
                .catch(() => alert('Document not found!'));
        });
}

但该链接试图获取一个名为“xxxx.com/download/filename”的文件。所以它停在“#”字符处。有什么方法可以完成这项工作,还是我必须用其他东西替换整个代码?

标签: javascriptfetchblob

解决方案


在 url 中,#指示发送到服务器的 url 部分的结尾以及告诉客户端在页面上滚动到哪个标题的“散列”或“片段”的开始。因此,# 之后的任何内容都将被服务器忽略。

通过将 # 替换为 url 编码的版本来修复它:%23。使用 自动执行此操作encodeURIComponent

encodeURIComponent('abc#.xlsx') === 'abc%23.xlsx'.

您只想对 last 之后的部分进行编码/,而不是对整个 url 进行编码。


推荐阅读