Skip to content

Support BASE64 file name encoding in ContentDisposition #26463

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -320,6 +323,7 @@ public static ContentDisposition empty() {
return new ContentDisposition("", null, null, null, null, null, null, null);
}

private final static Pattern BASE64_ENCODED_PATTERN = Pattern.compile("=\\?([0-9a-zA-Z-_]+)\\?B\\?([+/0-9a-zA-Z]+=*)\\?=");
/**
* Parse a {@literal Content-Disposition} header value as defined in RFC 2183.
* @param contentDisposition the {@literal Content-Disposition} header value
Expand Down Expand Up @@ -362,7 +366,14 @@ else if (attribute.equals("filename*") ) {
}
}
else if (attribute.equals("filename") && (filename == null)) {
filename = value;
final Matcher matcher = BASE64_ENCODED_PATTERN.matcher(value);
if (matcher.find()) {
String charsetName = matcher.group(1);
String encoded = matcher.group(2);
filename = new String(Base64.getDecoder().decode(encoded), Charset.forName(charsetName));
} else {
filename = value;
}
}
else if (attribute.equals("size") ) {
size = Long.parseLong(value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,18 @@ void parseEncodedFilenameWithPaddedCharset() {
.build());
}

@Test
void parseBase64EncodedUTF8Filename() {
assertThat(parse("attachment; filename=\"=?UTF-8?B?5pel5pys6KqeLmNzdg==?=\"").getFilename())
.isEqualTo("日本語.csv");
}

@Test
void parseBase64EncodedShiftJISFilename() {
assertThat(parse("attachment; filename=\"=?SHIFT_JIS?B?k/qWe4zqLmNzdg==?=\"").getFilename())
.isEqualTo("日本語.csv");
}

@Test
void parseEncodedFilenameWithoutCharset() {
assertThat(parse("form-data; name=\"name\"; filename*=test.txt"))
Expand Down