|
27 | 27 | import jakarta.activation.MimetypesFileTypeMap;
|
28 | 28 |
|
29 | 29 | import java.io.File;
|
30 |
| -import java.io.IOException; |
31 | 30 | import java.io.InputStream;
|
32 | 31 | import java.net.MalformedURLException;
|
33 | 32 | import java.net.URISyntaxException;
|
34 | 33 | import java.net.URL;
|
35 |
| -import java.nio.file.Files; |
36 |
| -import java.nio.file.InvalidPathException; |
37 |
| -import java.nio.file.Paths; |
| 34 | +import java.net.URLConnection; |
38 | 35 | import java.util.*;
|
39 | 36 | import java.util.stream.Collectors;
|
40 | 37 |
|
@@ -168,26 +165,31 @@ public String getMimeType(String file) {
|
168 | 165 | if (file == null || !file.contains(".")) {
|
169 | 166 | return null;
|
170 | 167 | }
|
171 |
| - String mimeType = null; |
172 |
| - try { |
173 |
| - mimeType = Files.probeContentType(Paths.get(file)); |
174 |
| - } catch (IOException | InvalidPathException e) { |
175 |
| - log("unable to probe for content type, will use fallback", e); |
176 |
| - } |
177 | 168 |
|
178 |
| - // MimetypesFileTypeMap is kept for backwards compatibility, remove in 2.0 |
| 169 | + // this implementation would be nice but returns null on Lambda |
| 170 | +// try { |
| 171 | +// mimeType = Files.probeContentType(Paths.get(file)); |
| 172 | +// } catch (IOException | InvalidPathException e) { |
| 173 | +// log("unable to probe for content type, will use fallback", e); |
| 174 | +// } |
| 175 | + |
179 | 176 | if (mimeTypes == null) {
|
180 | 177 | mimeTypes = new MimetypesFileTypeMap();
|
181 | 178 | }
|
182 |
| - String backwardsCompatibleMimeType = mimeTypes.getContentType(file); |
| 179 | + String mimeType = mimeTypes.getContentType(file); |
| 180 | + |
183 | 181 | // The getContentType method of the MimetypesFileTypeMap
|
184 | 182 | // returns MimetypesFileTypeMap.defaultType = application/octet-stream
|
185 |
| - // instead of null when the type cannot be found. |
186 |
| - if (mimeType == null || (backwardsCompatibleMimeType != null && !backwardsCompatibleMimeType.equals(mimeType) |
187 |
| - && !MediaType.APPLICATION_OCTET_STREAM.equals(backwardsCompatibleMimeType))) { |
188 |
| - log("using type " + backwardsCompatibleMimeType + " from MimetypesFileTypeMap for " + file |
189 |
| - + " instead of " + mimeType + " for backwards compatibility"); |
190 |
| - mimeType = backwardsCompatibleMimeType; |
| 183 | + // instead of null when the type cannot be found. trying to improve the result... |
| 184 | + if (mimeType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mimeType)) { |
| 185 | + try { |
| 186 | + String mimeTypeGuess = URLConnection.guessContentTypeFromName(new File(file).getName()); |
| 187 | + if (mimeTypeGuess !=null) { |
| 188 | + mimeType = mimeTypeGuess; |
| 189 | + } |
| 190 | + } catch (Exception e) { |
| 191 | + log("couldn't find a better contentType than " + mimeType + " for file " + file, e); |
| 192 | + } |
191 | 193 | }
|
192 | 194 |
|
193 | 195 | return mimeType;
|
|
0 commit comments