|
3 | 3 | import static java.util.Arrays.stream; |
4 | 4 |
|
5 | 5 | import java.io.IOException; |
| 6 | +import java.io.InputStream; |
6 | 7 | import java.util.List; |
7 | 8 | import java.util.Map; |
| 9 | +import java.util.stream.Collectors; |
| 10 | +import java.util.zip.ZipEntry; |
| 11 | +import java.util.zip.ZipInputStream; |
8 | 12 | import lombok.extern.slf4j.Slf4j; |
9 | 13 | import org.apache.tika.Tika; |
10 | 14 | import org.springframework.beans.factory.annotation.Value; |
11 | 15 | import org.springframework.http.MediaType; |
12 | 16 | import org.springframework.stereotype.Service; |
13 | 17 | import org.springframework.util.MimeType; |
14 | 18 | import org.springframework.web.multipart.MultipartFile; |
15 | | -import java.util.stream.Collectors; |
16 | 19 |
|
17 | 20 | /** |
18 | 21 | * This service is intended to help with miscellaneous file things. This service will help with checking mime types, both proper |
@@ -50,6 +53,8 @@ public class FileValidationService { |
50 | 53 | Map.entry(".odt", new MimeType("application", "vnd.oasis.opendocument.text")) |
51 | 54 | ); |
52 | 55 |
|
| 56 | + private final MimeType ZIP_MIME_TYPE = new MimeType("application", "zip"); |
| 57 | + |
53 | 58 | private final List<MimeType> ACCEPTED_MIME_TYPES; |
54 | 59 |
|
55 | 60 | private final List<String> ACCEPTED_FILE_EXTS; |
@@ -118,6 +123,22 @@ public Boolean isAcceptedMimeType(MultipartFile file) throws IOException { |
118 | 123 | if (file.getContentType() == null || file.getContentType().isBlank()) { |
119 | 124 | return false; |
120 | 125 | } |
| 126 | + |
| 127 | + MimeType mimeType = MimeType.valueOf(tikaFileValidator.detect(file.getInputStream())); |
| 128 | + |
| 129 | + if (ACCEPTED_MIME_TYPES.contains(FILE_EXT_MIME_TYPE_MAP.get(".docx")) && ZIP_MIME_TYPE.equals(mimeType)) { |
| 130 | + // docx files are technically just zip files with xml files inside of them. if the mime type is set to be a |
| 131 | + // zip file, and we accept docx files, we can check if the zip is actually a zip... or if it's a docx and return |
| 132 | + try (InputStream inputStream = file.getInputStream(); ZipInputStream zipInputStream = new ZipInputStream(inputStream)) { |
| 133 | + ZipEntry entry; |
| 134 | + while ((entry = zipInputStream.getNextEntry()) != null) { |
| 135 | + if (entry.getName().equals("word/document.xml") || entry.getName().equals("[Content_Types].xml")) { |
| 136 | + return true; |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + |
121 | 142 | return ACCEPTED_MIME_TYPES.contains(MimeType.valueOf(tikaFileValidator.detect(file.getInputStream()))); |
122 | 143 | } |
123 | 144 |
|
|
0 commit comments