Akka HTTP:ByteString作为表单数据请求中的文件有效负载

时间:2018-05-08 04:24:59

标签: scala facebook-graph-api akka akka-http

在我的一个previous questions中,我问过如何使用Akka HTTP表示表单数据请求?根据答案,我创建了一个工作样本,但面临着可扩展性"问题 - 当表单数据请求的数量很高时,我需要处理文件系统中的大量文件。

我很好奇,是否可以在表单数据请求中将ByteString作为文件有效负载发送?

case class FBSingleChunkUpload(accessToken: String, 
        sessionId: String,
        from: Long, 
        to: Long, 
        file: ByteString) //this property is received from S3 as array of bytes

我创建了以下示例:

def defaultEntity(content: String) =
  HttpEntity.Default(
    ContentTypes.`text/plain(UTF-8)`,
    content.length, Source(ByteString(content) :: Nil)
  )

def chunkEntity(chunk: ByteString) =
  HttpEntity.Strict(
    ContentType(MediaTypes.`application/octet-stream`),
    chunk
  )

val formData = Multipart.FormData(
  Source(
    Multipart.FormData.BodyPart("access_token", defaultEntity(upload.fbUploadSession.fbId.accessToken)) ::
    Multipart.FormData.BodyPart("upload_phase", defaultEntity("transfer")) ::
    Multipart.FormData.BodyPart("start_offset", defaultEntity(upload.fbUploadSession.from.toString)) ::
    Multipart.FormData.BodyPart("upload_session_id", defaultEntity(upload.fbUploadSession.uploadSessionId)) ::
    Multipart.FormData.BodyPart("video_file_chunk", chunkEntity(upload.chunk)) :: Nil
  )
)
val req = HttpRequest(
  HttpMethods.POST,
  s"/v2.3/${upload.fbUploadSession.fbId.pageId}/videos",
  Nil,
  formData.toEntity()
)

在这种情况下,Facebook向我发回一条消息:

  

您的视频上传在完成之前已超时。这是   可能是因为网络连接速度慢或因为视频   您尝试上传的内容太大

但是,如果我发送与ByteString相同的File,则可以正常使用。

这可能是什么原因?我已经尝试在MediaTypes.multipart/form-data中使用chunkEntity,但它的行为方式相同。

1 个答案:

答案 0 :(得分:1)

要将ByteString作为表单数据文件发送,您需要使用以下BodyPart

def fileEntity(chunk: ByteString) = Multipart.FormData.BodyPart.Strict("video_file_chunk",
    HttpEntity(ContentType(MediaTypes.`application/octet-stream`), chunk), Map("fileName" -> "video_chunk"))

要特别注意Map("fileName" -> "video_chunk")这些参数是必需的,以便正确构建表单数据HTTP请求。

因此,问题不是chunkEntity,而是使用此答案中的fileEntity:)