Corrupted data when sending chunks

I am trying to serve some blobs. Expected size of several gigs, so I figured the content should be sent in chunks.
For some reason I am getting corrupted responses when testing on video files/images. What am I missing?

fpath = "somefile.mkv"
conn =
      conn
      |> put_resp_content_type("application/octet-stream")
      |> put_resp_header("accept-ranges", "bytes")
      |> put_resp_header("content-disposition", "attachment; filename=\"somefile.mkv\"")
      |> send_chunked(200)

    File.stream!(fpath)
    |> Enum.reduce_while(conn, fn chunk, conn ->
      case chunk(conn, chunk) do
        {:ok, conn} -> {:cont, conn}
        {:error, :closed} -> {:halt, conn}
      end
    end)

The issue is due to line_or_bytes parameter in File.stream!.
By default it is set to :line. To stream binary files, it should be set to chunk size for reading. In the OP, using File.stream!(fpath, [], 512) fixes the issue.

2 Likes