Skip to content

Commit

Permalink
Strip bad ASCII chars from Content-Disposition (#13)
Browse files Browse the repository at this point in the history
Not all ASCII chars are even supported in practice in filenames in a Content-Disposition header. Strip out these characters as well as non-ASCII ones. This is based on the advice in RFC 6266 for implementing this header.
  • Loading branch information
sagebind authored Mar 9, 2020
1 parent a947211 commit 354ada3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/main/java/com/widen/urlbuilder/HttpUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@

public class HttpUtils
{
// Guidelines for generating this header: https://tools.ietf.org/html/rfc6266#appendix-D
public static String createContentDispositionHeader(String type, String filename)
{
// Most browsers don't normally support UTF-8 in HTTP headers (HTTP officially supports only ISO-8859-1). In
// practice, S3 only supports ASCII characters, so strip everything from the filename out not in the ASCII range.
// practice, S3 only supports ASCII characters, so strip everything from the filename out not in the ASCII
// range.
// In addition, many browsers do not support escape sequences or percent encoding properly either, so strip out
// the following characters: \ " %
String asciiFilename = Normalizer
.normalize(filename, Normalizer.Form.NFD)
.replaceAll("[^\\x20-\\x7E]", "");
.replaceAll("[^\\x20-\\x7E[\\\\\"%]]", "");

// Create the base header value.
String header = String.format("%s; filename=\"%s\"", type, asciiFilename);
Expand Down
16 changes: 16 additions & 0 deletions src/test/java/com/widen/urlbuilder/HttpUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,22 @@ public void testCreateContentDispositionHeader()
"inline; filename=\"foo.jpg\"",
HttpUtils.createContentDispositionHeader("inline", "foo.jpg")
);
assertEquals(
"inline; filename=\"hello world.jpg\"",
HttpUtils.createContentDispositionHeader("inline", "hello world.jpg")
);
assertEquals(
"inline; filename=\"helloworld.jpg\"; filename*=UTF-8''hello%22world.jpg",
HttpUtils.createContentDispositionHeader("inline", "hello\"world.jpg")
);
assertEquals(
"inline; filename=\"helloworld.jpg\"; filename*=UTF-8''hello%5Cworld.jpg",
HttpUtils.createContentDispositionHeader("inline", "hello\\world.jpg")
);
assertEquals(
"inline; filename=\"helloworld.jpg\"; filename*=UTF-8''hello%25world.jpg",
HttpUtils.createContentDispositionHeader("inline", "hello%world.jpg")
);
assertEquals(
"attachment; filename=\"+oo.jpg\"; filename*=UTF-8''%2B%C6%92oo.jpg",
HttpUtils.createContentDispositionHeader("attachment", "+ƒoo.jpg")
Expand Down

0 comments on commit 354ada3

Please sign in to comment.