@@ -10,6 +10,7 @@ import org.apache.pekko.http.scaladsl.server.Route
10
10
import org .apache .pekko .http .scaladsl .server .directives .FileInfo
11
11
import org .apache .pekko .http .scaladsl .settings .ConnectionPoolSettings
12
12
import org .apache .pekko .stream .scaladsl .FileIO
13
+ import org .apache .tika .Tika
13
14
import org .slf4j .{Logger , LoggerFactory }
14
15
15
16
import java .io .File
@@ -102,22 +103,24 @@ class Uploader(system: ActorSystem) {
102
103
result
103
104
}
104
105
106
+ def detectMediaType (file : File ): ContentType = {
107
+ val tika = new Tika ()
108
+ val detectedMediaType = tika.detect(file)
109
+ logger.info(s " Detected media type: $detectedMediaType" )
110
+
111
+ ContentType .parse(detectedMediaType) match {
112
+ case Right (contentType) => contentType
113
+ case Left (_) => ContentTypes .`application/octet-stream`
114
+ }
115
+ }
116
+
105
117
private def createEntityFrom (file : File ): Future [RequestEntity ] = {
106
118
require(file.exists())
107
119
val fileSource = FileIO .fromPath(file.toPath, chunkSize = 1000000 )
108
120
109
- // akka-http server is easy regarding the MediaType
110
- // Other HTTP servers need an explicit MediaType, to be able to process the multipart POST request
111
- // val paramMapFile = Map("type" -> "text/csv", "filename" -> file.getName)
112
- //
113
- // val formData = Multipart.FormData(Multipart.FormData.BodyPart(
114
- // "uploadedFile",
115
- // //HttpEntity(MediaTypes.`multipart/form-data`, file.length(), fileSource), paramMapFile))
116
- // HttpEntity(MediaTypes.`text/csv`.toContentType(HttpCharset.apply("UTF-8")(Seq.empty)), file.length(), fileSource), paramMapFile))
117
-
118
121
val formData = Multipart .FormData (Multipart .FormData .BodyPart (
119
122
" uploadedFile" ,
120
- HttpEntity (MediaTypes .`application/octet-stream` , file.length(), fileSource),
123
+ HttpEntity (detectMediaType(file) , file.length(), fileSource),
121
124
Map (" filename" -> file.getName)))
122
125
Marshal (formData).to[RequestEntity ]
123
126
}
0 commit comments