Support writing multipart non-ASCII file names

Issue: SPR-12108
This commit is contained in:
Rossen Stoyanchev
2014-09-25 18:00:55 -04:00
parent 6cbe1433e2
commit 9be0cf21e5
3 changed files with 48 additions and 2 deletions

View File

@@ -41,6 +41,8 @@ import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import javax.mail.internet.MimeUtility;
/**
* Implementation of {@link HttpMessageConverter} to read and write 'normal' HTML
* forms and also to write (but not read) multipart data (e.g. file uploads).
@@ -92,6 +94,8 @@ public class FormHttpMessageConverter implements HttpMessageConverter<MultiValue
private Charset charset = Charset.forName("UTF-8");
private Charset multipartCharset;
private List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
private List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
@@ -118,6 +122,18 @@ public class FormHttpMessageConverter implements HttpMessageConverter<MultiValue
this.charset = charset;
}
/**
* Set the character set to use when writing multipart data to encode file
* names. Encoding is based on the encoded-word syntax defined in RFC 2047
* and relies on the MimeUtility class from "javax.mail-api".
* <p>If not set file names will be encoded as US-ASCII.
* @param multipartCharset the charset to use
* @see <a href="http://en.wikipedia.org/wiki/MIME#Encoded-Word">Encoded-Word</a>
*/
public void setMultipartCharset(Charset multipartCharset) {
this.multipartCharset = multipartCharset;
}
/**
* Set the list of {@link MediaType} objects supported by this converter.
*/
@@ -374,7 +390,17 @@ public class FormHttpMessageConverter implements HttpMessageConverter<MultiValue
protected String getFilename(Object part) {
if (part instanceof Resource) {
Resource resource = (Resource) part;
return resource.getFilename();
String filename = resource.getFilename();
if (multipartCharset != null) {
try {
filename = MimeUtility.encodeText(filename, multipartCharset.name(), null);
}
catch (UnsupportedEncodingException e) {
// should not happen
throw new IllegalStateException(e);
}
}
return filename;
}
else {
return null;