From 7162c6ac0b033e835d29908ddea43368aa55b366 Mon Sep 17 00:00:00 2001 From: randy909 Date: Tue, 30 Oct 2018 11:08:33 -0500 Subject: [PATCH] Change when form parts go to files Rather than copy all form values to temp files when they have a content type defined, only copy when they specify a filename or when the content type is "application/octet-stream". Otherwise leave them as "normal" key-value pairs also using the charset to construct the strings. --- .../main/java/fi/iki/elonen/NanoHTTPD.java | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/core/src/main/java/fi/iki/elonen/NanoHTTPD.java b/core/src/main/java/fi/iki/elonen/NanoHTTPD.java index 75174f33..3fc58bde 100644 --- a/core/src/main/java/fi/iki/elonen/NanoHTTPD.java +++ b/core/src/main/java/fi/iki/elonen/NanoHTTPD.java @@ -790,13 +790,7 @@ private void decodeMultipartFormData(ContentType contentType, ByteBuffer fbuf, M parms.put(partName, values); } - if (partContentType == null) { - // Read the part into a string - byte[] data_bytes = new byte[partDataEnd - partDataStart]; - fbuf.get(data_bytes); - - values.add(new String(data_bytes, contentType.getEncoding())); - } else { + if (partIsFile(fileName, partContentType)) { // Read it into a file String path = saveTmpFile(fbuf, partDataStart, partDataEnd - partDataStart, fileName); if (!files.containsKey(partName)) { @@ -809,6 +803,17 @@ private void decodeMultipartFormData(ContentType contentType, ByteBuffer fbuf, M files.put(partName + count, path); } values.add(fileName); + } else { + // Read the part into a string + byte[] data_bytes = new byte[partDataEnd - partDataStart]; + fbuf.get(data_bytes); + + Matcher charsetMatcher = ContentType.CHARSET_PATTERN.matcher(partContentType == null ? "" : partContentType); + if (charsetMatcher.find()) { + values.add(new String(data_bytes, charsetMatcher.group(2))); + } else { + values.add(new String(data_bytes)); + } } } } catch (ResponseException re) { @@ -825,6 +830,10 @@ private int scipOverNewLine(byte[] partHeaderBuff, int index) { return ++index; } + private boolean partIsFile(String fileName, String partContentType) { + return fileName != null || "application/octet-stream".equals(partContentType); + } + /** * Decodes parameters in percent-encoded URI-format ( e.g. * "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given