Created
June 28, 2019 10:50
-
-
Save samuelorji/fceefa3b21dbd4b746c07b9435da8a0c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(path("upload") & extractLog) { log => | |
post { | |
entity(as[Multipart.FormData]) { formdata => | |
val partsSource = formdata.parts | |
val partsFlow = Flow[Multipart.FormData.BodyPart].map { fileData => { | |
if (fileData.name == "myFile") { | |
val filename = "./data/" + fileData.filename.getOrElse("tempFile_" + System.currentTimeMillis()) | |
val file = new File(filename) | |
val fileContentsSource = fileData.entity.dataBytes | |
Left(fileContentsSource, file) | |
} else { | |
Right(new RuntimeException("Not Expected File")) | |
} | |
} | |
} | |
val fileSink = Sink.fold[Future[IOResult], Either[(Source[ByteString, Any], File), RuntimeException]](Future(new IOResult(1L, Success(Done)))) { | |
case (_, Left((src, file))) => | |
src.runWith(FileIO.toPath(file.toPath)) | |
case (_, Right(ex)) => | |
Future(new IOResult(1L, Failure(ex))) | |
} | |
onComplete(partsSource.via(partsFlow).runWith(fileSink).flatten) { | |
case Success(value) => | |
value match { | |
case res@IOResult(_, _) => | |
if (res.wasSuccessful) complete("Successful Upload") | |
else { | |
log.error(s"Exception ${res.getError}") | |
complete("Unsuccessful Upload") | |
} | |
} | |
case Failure(ex) => | |
log.error(s"Exception Received $ex") | |
complete("Unsuccessful Upload") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment