我正在尝试使用 akka http 实现简单的文件上传。我的尝试如下所示:
import akka.actor.ActorSystem
import akka.event.{LoggingAdapter, Logging}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpResponse, HttpRequest}
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.stream.{ActorMaterializer, Materializer}
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import scala.concurrent.{ExecutionContextExecutor, Future}
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.HttpEntity
import java.io._
import akka.stream.io._
object UploadTest extends App {
implicit val system = ActorSystem()
implicit val executor = system.dispatcher
implicit val materializer = ActorMaterializer()
val config = ConfigFactory.load()
val logger = Logging(system, getClass)
val routes = {
pathSingleSlash {
(post & extractRequest) {
request => {
val source = request.entity.dataBytes
val outFile = new File("/tmp/outfile.dat")
val sink = SynchronousFileSink.create(outFile)
source.to(sink).run()
complete(HttpResponse(status = StatusCodes.OK))
}
}
}
}
Http().bindAndHandle(routes, config.getString("http.interface"), config.getInt("http.port"))
}
这段代码有几个问题:
- 无法上传大于配置实体大小的文件:
Request Content-Length 24090745 exceeds the configured limit of 8388608
- 连续执行两次上传会导致
dead letters encountered.
异常。
克服大小限制的最佳方法是什么?如何正确关闭文件,以便后续上传将覆盖现有文件(暂时忽略并发上传)?