How to encode the filename parameter of Content-Disposition header in HTTP?

前端 未结 18 1754
北荒
北荒 2020-11-21 06:15

Web applications that want to force a resource to be downloaded rather than directly rendered in a Web browser issue a Content-Disposition hea

18条回答
  •  无人及你
    2020-11-21 07:14

    • There is no interoperable way to encode non-ASCII names in Content-Disposition. Browser compatibility is a mess.

    • The theoretically correct syntax for use of UTF-8 in Content-Disposition is very weird: filename*=UTF-8''foo%c3%a4 (yes, that's an asterisk, and no quotes except an empty single quote in the middle)

    • This header is kinda-not-quite-standard (HTTP/1.1 spec acknowledges its existence, but doesn't require clients to support it).

    There is a simple and very robust alternative: use a URL that contains the filename you want.

    When the name after the last slash is the one you want, you don't need any extra headers!

    This trick works:

    /real_script.php/fake_filename.doc
    

    And if your server supports URL rewriting (e.g. mod_rewrite in Apache) then you can fully hide the script part.

    Characters in URLs should be in UTF-8, urlencoded byte-by-byte:

    /mot%C3%B6rhead   # motörhead
    

提交回复
热议问题