如何将apache poi xls工作簿直接流到akka-http响应?

问题描述 投票:0回答:1

是否有办法 避开 把Apache POI工作簿写成字节数组或临时文件,然后流到akka-http响应中就可以了吗?

val wb = new SXSSFWorkbook(new XSSFWorkbook())
...building workbook...
val os = new ByteArrayOutputStream() //or buffered file output stream
wb.write(os) // <- can I just get from akka-http some output stream to write workbook directly to response?
scala apache-poi akka-stream akka-http
1个回答
1
投票

这就是你如何通过一个 Source[ByteString, _] 作为 complete 航线

val route: Route = get {
  val (out, source) = StreamConverters.asOutputStream().preMaterialize()
  writeAsync(out)
  complete(HttpEntity(ContentTypes.`application/octet-stream`, source))
}

writeAsync 可能是这样的,但你需要使用 new SXSSFWorkbook(new XSSFWorkbook()).write(os) 此处

def writeAsync(out: OutputStream): Unit = {
  val random = new Random()
  Future {
    1 until 10000 foreach { _ =>
      out.write(random.nextPrintableChar().toInt)
    }
    out.close()
  }
}

方法 out.write 将被封锁,直到有需求发送给 Source. 封锁的超时时间是通过以下方式配置的 asOutputStream() 办法

© www.soinside.com 2019 - 2024. All rights reserved.