Fetch 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"。所以它停在"#"性格有什么方法可以让它工作吗?或者我必须用其他东西替换整个代码吗?

在url中,#表示发送到服务器的url部分的结束和";hash";或";片段";其告诉客户端在页面上滚动到哪个标题。因此,#之后的任何内容都将被服务器忽略。

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

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

您希望只对最后一个/之后的部分进行编码,而不是对整个url进行编码。

最新更新