V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zhongs
V2EX  ›  前端开发

请问个前端问题?

  •  
  •   zhongs · 262 天前 · 810 次点击
    这是一个创建于 262 天前的主题,其中的信息可能已经有所发展或是发生改变。

    接口请求头返回得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]
    
    7 条回复    2023-08-10 16:46:33 +08:00
    sailei
        1
    sailei  
       262 天前
    decodeURIComponent(str)
    gkinxin
        2
    gkinxin  
       262 天前
    ```
    let params = new URLSearchParams(document.location.search);
    let name = params.get("filename");
    ```
    gkinxin
        3
    gkinxin  
       262 天前
    @gkinxin #2 看错问题,请忽略
    me1onsoda
        4
    me1onsoda  
       262 天前
    很明显是 url 编码,这居然不解码
    Danswerme
        5
    Danswerme  
       262 天前
    decodeURIComponent(str).split(";")[1].split('=')[1]
    jifengg
        6
    jifengg  
       262 天前
    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”进行搜索
    grit136907108
        7
    grit136907108  
       260 天前   ❤️ 1
    const regex = /filename=(.*?)(?:;|$)/;
    const match = str.match(regex);
    const filename = match ? decodeURIComponent(match[1]) : null;
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2804 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 06:12 · PVG 14:12 · LAX 23:12 · JFK 02:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.