如何设置从ByteString创建的HttpRequest / HttpEntity的块大小

时间:2019-01-15 21:36:44

标签: akka-http

如果我要上传akka-http中的文件,可以使用类似的方法来控制块大小:

  private def createUploadRequest(streamName: String, uri: Uri, path: Path): Future[(HttpRequest, Path)] = {
    val bodyPart = FormData.BodyPart.fromPath("data", ContentTypes.`application/octet-stream`, path, chunkSize)
    val body     = FormData(bodyPart) 
    Marshal(body).to[RequestEntity].map { entity => 
      HttpRequest(method = HttpMethods.POST, uri = uri, entity = entity) -> path
    }
  }

但是,如果我只有一个带有内容的ByteString并想上传它,我将无法控制块的大小:

  private def makeHttpRequest(streamName: String, serverInfo: ServerInfo, bs: ByteString): HttpRequest = {
    HttpRequest(
      HttpMethods.POST,
      s"http://${serverInfo.host}:${serverInfo.port}$distRoute/$streamName",
      entity = HttpEntity(ContentTypes.`application/octet-stream`, bs)
    )
  }

从ByteString创建HttpEntity时,有什么方法可以控制块的大小吗?

2 个答案:

答案 0 :(得分:0)

创建一个Chunked实体,而不使用HttpEntity.apply方法:

import akka.http.scaladsl.model.HttpEntity.Chunked
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart

type ChunkSize = Int

val chunkedEntityFromByteString : ChunkSize => ByteString => Entity = 
  chunkSize => byteString =>
    Chunked(
      ContentTypes.`application/octet-stream`,
      Source
        .fromIterator(() => byteString sliding chunkSize)
        .map(ChunkStreamPart.apply)
    )

答案 1 :(得分:0)

只需稍稍修正一下发布的解决方案即可使其编译:

    type ChunkSize = Int

    val chunkedFromByteString : ChunkSize => ByteString => HttpEntity =
      chunkSize => byteString =>
        Chunked(
          ContentTypes.`application/octet-stream`,
          Source
            .fromIterator(() => byteString sliding chunkSize)
            .map(ChunkStreamPart.apply)
        )