Skip to content

Commit

Permalink
Improve decoding support for multipart filename
Browse files Browse the repository at this point in the history
StandardMultipartHttpServletRequest now properly decodes RFC-5987
encoded filenames (i.e. filename*) by delegating to ContentDisposition
and also support RFC-2047 syntax through javax.mail MimeUtility.

Issue: SPR-15205
  • Loading branch information
rstoyanchev committed Jul 20, 2017
1 parent 2437500 commit bb684ce
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
Expand All @@ -31,9 +30,11 @@
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.FileCopyUtils;
Expand All @@ -54,13 +55,6 @@
*/
public class StandardMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest {

private static final String CONTENT_DISPOSITION = "content-disposition";

private static final String FILENAME_KEY = "filename=";

private static final String FILENAME_WITH_CHARSET_KEY = "filename*=";


@Nullable
private Set<String> multipartParameterNames;

Expand Down Expand Up @@ -96,12 +90,13 @@ private void parseRequest(HttpServletRequest request) {
this.multipartParameterNames = new LinkedHashSet<>(parts.size());
MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<>(parts.size());
for (Part part : parts) {
String disposition = part.getHeader(CONTENT_DISPOSITION);
String filename = extractFilename(disposition);
if (filename == null) {
filename = extractFilenameWithCharset(disposition);
}
String headerValue = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
ContentDisposition disposition = ContentDisposition.parse(headerValue);
String filename = disposition.getFilename();
if (filename != null) {
if (filename.startsWith("=?") && filename.endsWith("?=")) {
filename = MimeDelegate.decode(filename);
}
files.add(part.getName(), new StandardMultipartFile(part, filename));
}
else {
Expand All @@ -123,62 +118,6 @@ protected void handleParseFailure(Throwable ex) {
throw new MultipartException("Failed to parse multipart servlet request", ex);
}

@Nullable
private String extractFilename(String contentDisposition, String key) {
int startIndex = contentDisposition.indexOf(key);
if (startIndex == -1) {
return null;
}
String filename = contentDisposition.substring(startIndex + key.length());
if (filename.startsWith("\"")) {
int endIndex = filename.indexOf("\"", 1);
if (endIndex != -1) {
return filename.substring(1, endIndex);
}
}
else {
int endIndex = filename.indexOf(";");
if (endIndex != -1) {
return filename.substring(0, endIndex);
}
}
return filename;
}

@Nullable
private String extractFilename(String contentDisposition) {
return extractFilename(contentDisposition, FILENAME_KEY);
}

@Nullable
private String extractFilenameWithCharset(String contentDisposition) {
String filename = extractFilename(contentDisposition, FILENAME_WITH_CHARSET_KEY);
if (filename == null) {
return null;
}
int index = filename.indexOf("'");
if (index != -1) {
Charset charset = null;
try {
charset = Charset.forName(filename.substring(0, index));
}
catch (IllegalArgumentException ex) {
// ignore
}
filename = filename.substring(index + 1);
// Skip language information..
index = filename.indexOf("'");
if (index != -1) {
filename = filename.substring(index + 1);
}
if (charset != null) {
filename = new String(filename.getBytes(StandardCharsets.US_ASCII), charset);
}
}
return filename;
}


@Override
protected void initializeMultipart() {
parseRequest(getRequest());
Expand Down Expand Up @@ -322,4 +261,20 @@ public void transferTo(File dest) throws IOException, IllegalStateException {
}
}


/**
* Inner class to avoid a hard dependency on the JavaMail API.
*/
private static class MimeDelegate {

public static String decode(String value) {
try {
return MimeUtility.decodeText(value);
}
catch (UnsupportedEncodingException ex) {
throw new IllegalStateException(ex);
}
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.multipart.support;

import org.junit.Test;

import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockPart;
import org.springframework.web.multipart.MultipartFile;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
* Unit tests for {@link StandardMultipartHttpServletRequest}.
* @author Rossen Stoyanchev
*/
public class StandardMultipartHttpServletRequestTests {


@Test
public void filename() throws Exception {

StandardMultipartHttpServletRequest request = getRequest(
"file", "form-data; name=\"file\"; filename=\"myFile.txt\"");

MultipartFile multipartFile = request.getFile("file");
assertNotNull(multipartFile);
assertEquals("myFile.txt", multipartFile.getOriginalFilename());
}

@Test // SPR-13319
public void filenameRfc5987() throws Exception {

StandardMultipartHttpServletRequest request = getRequest(
"file", "form-data; name=\"file\"; filename*=\"UTF-8''foo-%c3%a4-%e2%82%ac.html\"");

MultipartFile multipartFile = request.getFile("file");
assertNotNull(multipartFile);
assertEquals("foo-ä-€.html", multipartFile.getOriginalFilename());
}

@Test // SPR-15205
public void filenameRfc2047() throws Exception {

StandardMultipartHttpServletRequest request = getRequest(
"file", "form-data; name=\"file\"; filename=\"=?UTF-8?Q?Declara=C3=A7=C3=A3o.pdf?=\"");

MultipartFile multipartFile = request.getFile("file");
assertNotNull(multipartFile);
assertEquals("Declaração.pdf", multipartFile.getOriginalFilename());
}


private StandardMultipartHttpServletRequest getRequest(String name, String dispositionValue) {
MockHttpServletRequest request = new MockHttpServletRequest();
MockPart part = new MockPart(name, new byte[0]);
part.getHeaders().set("Content-Disposition", dispositionValue);
request.addPart(part);
return new StandardMultipartHttpServletRequest(request);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ public ResponseEntity<Object> create(@RequestPart(name = "json-data") TestData t

@RequestMapping(value = "/spr13319", method = POST, consumes = "multipart/form-data")
public ResponseEntity<Void> create(@RequestPart("file") MultipartFile multipartFile) {
assertEquals("%C3%A9l%C3%A8ve.txt", multipartFile.getOriginalFilename());
assertEquals("élève.txt", multipartFile.getOriginalFilename());
return ResponseEntity.ok().build();
}
}
Expand Down

0 comments on commit bb684ce

Please sign in to comment.