javascript - 获取 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 部分的结尾以及告诉客户端在页面上滚动到哪个标题的“散列”或“片段”的开始。因此,# 之后的任何内容都将被服务器忽略。
通过将 # 替换为 url 编码的版本来修复它:%23
。使用 自动执行此操作encodeURIComponent
。
encodeURIComponent('abc#.xlsx') === 'abc%23.xlsx'.
您只想对 last 之后的部分进行编码/
,而不是对整个 url 进行编码。
推荐阅读
- linux - Bash 脚本 sftp 仅将文件下载到同一目录脚本位于
- oracle - 如何使用kerberized身份验证代理到Oracle数据库链接中的另一个数据库用户
- python - 将 Django 从 2.1 升级到 2.2.13 时如何修复 pyodbc 依赖错误?
- openstack - openstack 错误:virNetSocketReadWire:1806:读取数据时文件结束:输入/输出错误
- python - 使用 BeautifulSoup 在 Python 中抓取特定的 div
- php - 使用键和值创建PHP数组时如何分配变量
- mongodb - 如何在 MongoDB 中的 $group 内创建嵌套数组?
- sql - 定期进行 DB 到 DB 映射
- javascript - 如何获取嵌套打字稿接口的json字符串
- azure - 使用 Azure B2C 自定义策略获取 userPrinciaplName