0

I am new to AKKA world,

How to send a file as a response using akka http?

I got a solution for how to send the file in RESTAPI response with Akka-HTTP, from the above post but I want to provide a name and extension to that file. so what is a way to send the file as a response with filename and extension means I want downloaded file should have a name with .zip extension in Akka-HTTP with scala

1 Answers1

0

Adding onto the other answer you can use the Akka HTTP DSL as follows:



  val fileContentsSource: (String, String) => Source[ChunkStreamPart, _] =
    (fileName, enc) =>
      Source
        .fromIterator(() => scala.io.Source.fromFile(fileName, enc).getLines)
        .map(ChunkStreamPart.apply)


  val fileEntityResponse: (String, String) => HttpResponse =
    (fileName, enc) =>
      HttpResponse(entity = Chunked(ContentTypes.`text/plain(UTF-8)`,
        fileContentsSource(fileName, enc)))



  val route: Route = {
    path("file" / Segment) { fileName =>
      complete(fileEntityResponse(fileName, "UTF-8"))
    }
  }

The Segment is called a PathMatcher and will extract the file name from the route so call it as follows

curl --location --request GET 'localhost:PORT/file/filename.txt'
Titan Chase
  • 101
  • 1
  • 6