简体   繁体   中英

Create and stream a zip file as it is beeing created with the playframework and scala

My scala-play api provides endpoints to return a file as a stream via the Ok.chunked -function.

I now want to be able to allow the download of multiple files as a zip archive.

I want to create a zip file as a stream which play should directly return as a filestream. Meaning without the need to temporarly save the zip-file on the disc and serving it while it is being created.

What would be a good way to implemente a function that creates this stream?

I solved the issue by using akkas alpakka.

import akka.stream.alpakka.file.ArchiveMetadata
import akka.stream.alpakka.file.scaladsl.Archive
import akka.stream.scaladsl.Source
import akka.util.ByteString

val fileSource: Source[ByteString, _]  = FileIO.fromPath(path)
val tupelWithMetaData = (ArchiveMetadata(s"file.txt"), fileSource)

val stream: Source[ByteString, _] = Source(List(tupelWithMetaData)).via(Archive.zip())

First I create a akka ByteString source. The source is used inside the Tupel2 with some ArchiveMetadata . This tuple can than be used to create a new source which can be connected to alpakkas Archive.zip() .

The resulting stream can than be used with plays Ok.chunked .

I hope this solution might help you if you have the same question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM