如何解析包含 UTF-8 字符的 Content-Disposition headers

How to parse Content-Disposition headers that contain UTF-8 characters

我正在尝试使用 client-side JavaScript 解析 HTTP Content-Disposition headers。当文件名由 ASCII 字符组成时,这很容易。但是当涉及 non-ASCII 个字符时,header 看起来像这样:

Content-Disposition:attachment; filename="john?doe.jpg"; filename*=UTF-8''john%E2%80%93doe.jpg

我可以使用 content-disposition npm 包在 Node.js 中解析它。我尝试在 client-side 代码中使用这个包,但它在下一行失败,因为浏览器(例如 Chrome)不支持 Buffer class:

value = new Buffer(binary, 'binary').toString('utf8')

任何人都可以告诉我使用 client-side JavaScript 解析这些 header 的另一种方法,或者用其他方法替换 Buffer 的这种用法的方法吗?

我四处寻找解决方案,但每次有人问如何解析 content-disposition header,答案只适用于 ASCII 的情况。

在网络浏览器中,您可以使用:

decodeURIComponent('john%E2%80%93doe.jpg')

decodeURIComponent是为%编码的字节设计的,代表文本,假定Unicode字符集的UTF-8字符编码。