storeUploadedFiles
Description
Streams the contents of all files uploaded in a multipart form into files on disk and provides a list of each file and metadata about the upload.
If there is an error writing to disk the request will be failed with the thrown exception. If there is no field with the given name the request will be rejected.
Example
- Scala
-
source
def tempDestination(fileInfo: FileInfo): File = File.createTempFile(fileInfo.fileName, ".tmp") val route = storeUploadedFiles("csv", tempDestination) { files => val finalStatus = files.foldLeft(StatusCodes.OK) { case (status, (metadata, file)) => // do something with the file and file metadata ... file.delete() status } complete(finalStatus) } // tests: val multipartForm = Multipart.FormData( Multipart.FormData.BodyPart.Strict( "csv", HttpEntity(ContentTypes.`text/plain(UTF-8)`, "2,3,5\n7,11,13,17,23\n29,31,37\n"), Map("filename" -> "primesA.csv")), Multipart.FormData.BodyPart.Strict( "csv", HttpEntity(ContentTypes.`text/plain(UTF-8)`, "41,43,47\n53,59,6167,71\n73,79,83\n"), Map("filename" -> "primesB.csv"))) Post("/", multipartForm) ~> route ~> check { status shouldEqual StatusCodes.OK } - Java
-
source
import static org.apache.pekko.http.javadsl.server.Directives.complete; import static org.apache.pekko.http.javadsl.server.Directives.storeUploadedFiles; final Function<FileInfo, File> temporaryDestination = info -> { try { return File.createTempFile(info.getFileName(), ".tmp"); } catch (Exception e) { return null; } }; final Route route = storeUploadedFiles( "csv", temporaryDestination, files -> { files.forEach( item -> { // do something with the file and file metadata ... FileInfo info = item.getKey(); File file = item.getValue(); file.delete(); }); return complete(StatusCodes.OK); }); Map<String, String> filenameMappingA = new HashMap<>(); Map<String, String> filenameMappingB = new HashMap<>(); filenameMappingA.put("filename", "primesA.csv"); filenameMappingB.put("filename", "primesB.csv"); org.apache.pekko.http.javadsl.model.Multipart.FormData multipartForm = Multiparts.createStrictFormDataFromParts( Multiparts.createFormDataBodyPartStrict( "csv", HttpEntities.create( ContentTypes.TEXT_PLAIN_UTF8, "2,3,5\n7,11,13,17,23\n29,31,37\n"), filenameMappingA), Multiparts.createFormDataBodyPartStrict( "csv", HttpEntities.create( ContentTypes.TEXT_PLAIN_UTF8, "41,43,47\n53,59,61,67,71\n73,79,83\n"), filenameMappingB)); // test: testRoute(route) .run( HttpRequest.POST("/") .withEntity(multipartForm.toEntity(BodyPartRenderer.randomBoundaryWithDefaults()))) .assertStatusCode(StatusCodes.OK);
1.0.1