zhongs

请问个前端问题?

  •  
  •   zhongs · Aug 8, 2023 · 2072 views
    This topic created in 1182 days ago, the information mentioned may be changed or developed.

    接口请求头返回得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 replies  •  2023-08-10 16:46:33 +08:00
    sailei
    sailei
    Aug 8, 2023
    1
    decodeURIComponent(str)
    oky
    oky
    Aug 8, 2023
    2
    ```
    let params = new URLSearchParams(document.location.search);
    let name = params.get("filename");
    ```
    oky
    oky
    Aug 8, 2023
    3
    @gkinxin #2 看错问题,请忽略
    me1onsoda
    me1onsoda
    Aug 8, 2023
    4
    很明显是 url 编码,这居然不解码
    Danswerme
    Danswerme
    Aug 8, 2023
    5
    decodeURIComponent(str).split(";")[1].split('=')[1]
    jifengg
    jifengg
    Aug 9, 2023
    6
    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”进行搜索
    liuwb
    liuwb
    Aug 10, 2023❤️1
    7
    const regex = /filename=(.*?)(?:;|$)/;
    const match = str.match(regex);
    const filename = match ? decodeURIComponent(match[1]) : null;
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5071 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 08:33 · PVG 16:33 · LAX 00:33 · JFK 03:33
    ♥ Do have faith in what you're doing.