Fetch blob处理文件名包含#字符的URL时请求异常该如何解决?
问题根源
#是URL中的哈希(fragment)标识符,浏览器发起HTTP请求时会自动丢弃#及之后的内容,不会传递给服务端,因此你请求带#的文件名时会出现截断问题,不需要完全替换现有代码,仅需对URL做编码处理即可解决。
解决方法
对返回的URL中路径部分的#字符进行百分号编码,转义为%23即可。如果后端返回的URL没有提前编码,可以在前端调用encodeURI()方法对完整URL做编码处理,注意不要用encodeURIComponent(),该方法会把/之类的路径分隔符也编码,导致URL失效。
修改后的代码示例
// This is only a helper class for Ajax request new SimpleAjaxRequest().safeRequest("mainpage/downloaddocument.php", { questionnaireid: questionnaire.id }, true, false, (response) => { // 对URL编码,转义#等特殊字符 const encodedUrl = encodeURI(response.data.url); fetch(encodedUrl) // 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; // 文件名带#无需额外处理,download属性支持直接使用 a.download = response.data.name; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); // 补充清理冗余DOM节点 }) .catch(() => alert('Document not found!')); });
补充说明
- 优先建议后端返回URL时就对路径中的特殊字符做编码处理,从源头上避免此类问题
- 如果你还需要处理其他路径中的特殊字符(比如空格、中文、&等),
encodeURI()方法同样可以正确转义,不会破坏URL本身的结构
内容的提问来源于stack exchange,提问作者Thallius
相关产品推荐
相关产品推荐

