How to set filename containing spaces in Content-Disposition header

妖精的绣舞 提交于 2019-11-29 05:24:20

Use quotes:

resp.addHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");

According to the HTTP standard you surround the string with double-quotes, and escape any quotes or backslashes within by preceding them with a single backslash.

Content-Disposition: attachment; filename="Very \"interesting\" file \\ files.txt"

This will prompt to save as Very "interesting" file \ files.txt. Note that the presence of a backslash does not suggest a folder, it suggests the backslash is part of the filename (which is perfectly valid on Linux and some other platforms, but not on Windows.)

Raphaël

if you quote your filename with chr(34) it will work:

resp.addHeader("Content-Disposition", "inline; filename=" + chr(34) + fileName + chr(34));

Following steps are required:

  • URI-encode the filename
  • Replace the spaces in the encoded filename (we're using an URL encoder instead of URI encoder, but URL encoding uses + as encoded space instead of %20, so we need to manually replace them with %20).
  • Set the encoded file name in the header. Here we have two variants: one which specifices the encoding, and one that doesn't. For maximal compatibility we can specify both.

Code:

String fileName = ...;
String encodedFileName = URLEncoder.encode(fileName, 
    StandardCharsets.UTF_8.name()).replace("+", "%20");

response.setHeader("Content-Disposition", 
    String.format("inline; filename*=UTF-8''%1$s; filename=%1$s", encodedFileName));

Example header: inline; filename*=UTF-8''Hello%20World.doc; filename=Hello%20World.doc

Successfully tested with

  • Firefox ✔
  • Chrome ✔
  • Edge ✔
  • Internet Explorer ✔
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!