
接口请求头返回得Content-Disposition信息如下,想截取 filename 数据,有没有更好的代码获取方式?
attachment; filename=%E6%B5%B7%E5%85%B3%E8%BE%B9%E6%A3%80%E6%95%B0%E6%8D%AE%E5%87%BA%E5%85%A5%E5%A2%83%E6%95%B0%E6%8D%AE%E8%A1%A8.xlsx 目前获取方式
const str = 'attachment; filename=%E6%B5%B7%E5%85%B3%E8%BE%B9%E6%A3%80%E6%95%B0%E6%8D%AE%E5%87%BA%E5%85%A5%E5%A2%83%E6%95%B0%E6%8D%AE%E8%A1%A8.xlsx' const filename = str.split('=')[1] 1 sailei 2023-08-08 17:46:53 +08:00 decodeURIComponent(str) |
2 gkinxin 2023-08-08 18:16:22 +08:00 ``` let params = new URLSearchParams(document.location.search); let name = params.get("filename"); ``` |
4 me1onsoda 2023-08-08 18:21:29 +08:00 很明显是 url 编码,这居然不解码 |
5 Danswerme 2023-08-08 18:29:35 +08:00 decodeURIComponent(str).split(";")[1].split('=')[1] |
6 jifengg 2023-08-09 09:13:28 +08:00 http header 有规范,以上直接截取的方式,只适合特定内容的。 MDN: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Disposition 如果是 js 代码,推荐使用 https://www.npmjs.com/package/content-disposition 库进行解析。 其他语言可以按照关键词“Content-Disposition”进行搜索 |
7 liuwb 2023-08-10 16:46:33 +08:00 const regex = /filename=(.*?)(?:;|$)/; const match = str.match(regex); const filename = match ? decodeURIComponent(match[1]) : null; |