storeUploadedFile

Signature

def storeUploadedFile(fieldName: String, destFn: FileInfo 

Description

Streams the contents of a file uploaded as a multipart form into a file on disk and provides the 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. If there are multiple file parts with the same name, the first one will be used and the subsequent ones ignored.

Note

This directive will stream contents of the request into a file, however one can not start processing these until the file has been written completely. For streaming APIs it is preferred to use the fileUpload directive, as it allows for streaming handling of the incoming data bytes.

Example

Scala
source
def tempDestination(fileInfo: FileInfo): File = File.createTempFile(fileInfo.fileName, ".tmp") val route = storeUploadedFile("csv", tempDestination) { case (metadata, file) => // do something with the file and file metadata ... file.delete() complete(StatusCodes.OK) } // 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" -> "primes.csv"))) Post("/", multipartForm) ~> route ~> check { status shouldEqual StatusCodes.OK }
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.storeUploadedFile;

final Function<FileInfo, File> temporaryDestination =
    (info) -> {
      try {
        return File.createTempFile(info.getFileName(), ".tmp");
      } catch (Exception e) {
        return null;
      }
    };

final Route route =
    storeUploadedFile(
        "csv",
        temporaryDestination,
        (info, file) -> {
          // do something with the file and file metadata ...
          file.delete();
          return complete(StatusCodes.OK);
        });

Map<String, String> filenameMapping = new HashMap<>();
filenameMapping.put("filename", "primes.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"),
            filenameMapping));

// test:
testRoute(route)
    .run(
        HttpRequest.POST("/")
            .withEntity(multipartForm.toEntity(BodyPartRenderer.randomBoundaryWithDefaults())))
    .assertStatusCode(StatusCodes.OK);