From 513c5d5c03fbea10d9e228a8218db3565fc5da90 Mon Sep 17 00:00:00 2001 From: Kaloyan Raev Date: Tue, 3 Apr 2018 22:38:24 +0300 Subject: [PATCH] Escape file name before guessing mime type (#13) Fixes https://github.com/Storj/android-libstorj/issues/24 --- src/main/java/io/storj/libstorj/File.java | 13 +++++++- src/test/java/io/storj/libstorj/FileTest.java | 31 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/test/java/io/storj/libstorj/FileTest.java diff --git a/src/main/java/io/storj/libstorj/File.java b/src/main/java/io/storj/libstorj/File.java index 776b74c..5cfbcbb 100644 --- a/src/main/java/io/storj/libstorj/File.java +++ b/src/main/java/io/storj/libstorj/File.java @@ -18,6 +18,8 @@ import java.io.Serializable; import java.net.URLConnection; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Objects; /** @@ -175,12 +177,21 @@ public long getSize() { * @return a guess of the content type based on the file name */ public String getMimeType() { + String mime = null; + // prefer the Java util as libstorj returns always 'application/octet-stream' - String mime = URLConnection.guessContentTypeFromName(name); + try { + String escaped = URLEncoder.encode(name, StandardCharsets.UTF_8.toString()); + mime = URLConnection.guessContentTypeFromName(escaped); + } catch (Exception e) { + // mime will remain null + } + if (mime == null || mime.isEmpty()) { // fallback to libstorj mime = mimeType; } + return mime; } diff --git a/src/test/java/io/storj/libstorj/FileTest.java b/src/test/java/io/storj/libstorj/FileTest.java new file mode 100644 index 0000000..895d0a6 --- /dev/null +++ b/src/test/java/io/storj/libstorj/FileTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2018 Kaloyan Raev + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ +package io.storj.libstorj; + +import org.junit.Assert; +import org.junit.Test; + +public class FileTest { + + @Test + public void testMimeType() { + File file = new File("file-id", "bucket-id", "A#BC.pdf", null, true, 1, null, null, + null, null); + Assert.assertEquals("application/pdf", file.getMimeType()); + } + +}