LoginSignup
0
0

More than 3 years have passed since last update.

http4sでCSVファイルをダウンロード

Last updated at Posted at 2020-04-03

はじめに

http4sを使ってCSVファイルをダウンロードさせたかったけれども、全くと言っていいほど資料が出てこなかったので書いておく。

環境

  • Scala: 12.13
  • http4s: 0.21

結論

どうやらhttp4sに使われてるfs2Streamを利用してCSVの行を生成して適当なヘッダーを付けてレスポンスを返してやればよさそう(Excelで開きたかったら先頭にBomを付けてやる必要あり)。

適時importしてください。

val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {
  case GET -> Root / "download" =>
    val bom = Stream.chunk(Chunk[Byte](0xef.toByte, 0xbb.toByte, 0xbf.toByte))
    val csv = Stream.evalSeq(List("a,b,c","1,2,3")).intersperse("\n").through(fs2.text.utf8Encode)
    val stream = bom ++ csv

    Ok(
      stream,
      `Content-Type`(MediaType.text.csv, Charset.`UTF-8`),
      `Content-Disposition`("attachment", Map("filename" -> "file.csv")))
}

これでブラウザからURLをたたけばCSVファイルがダウンロードされるはず。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0