Elm中Http.get中的字节解码

3

我对 Elm 还比较陌生,目前遇到了一个关于从后端获取数据填充模型的问题。我可以向服务器发起 GET 请求并返回一个字节数组(数据可能是任何类型的图像、音频或视频),当使用 Html.img 显示这些数据时,一切都运行良好。但是,当我尝试使用 Http.get (src:https://package.elm-lang.org/packages/elm/http/latest/Http) 来填充我的模型时,它需要解码器。问题在于 Bytes.Decode.bytes 需要一个整数来知道需要解码多少个字节。

所以我的问题是:有没有办法在仍然匹配 Http.get 的类型模式的情况下访问字节宽度?

以下是我的问题的简单示例:


import Bytes exposing (Bytes)
import Bytes.Decode exposing (Decoder, bytes, decode)
import GeneralTypes exposing (Msg(..))
import Http

getMediaFromUrl : Cmd Msg
getMediaFromUrl = Http.get
        { url = "http://localhost:8090/image/2006/aa@a.de/session"
        , expect = Http.expectBytes GetThumbnail decodeBytes
        }

decodeBytes: Bytes.Bytes -> Decoder Bytes
decodeBytes bytesToDecode= let
                fileSize =
                    bytesToDecode |> Bytes.width
              in
              Bytes.Decode.bytes fileSize

module GeneralTypes exposing (..)

import Bytes exposing (Bytes)
import Http

type Msg = GetThumbnail (Result Http.Error Bytes)

文档中获取字节字符串宽度的示例(https://package.elm-lang.org/packages/elm/bytes/latest/Bytes-Decode#strings)是否有助于您的情况? - simplystuart
1个回答

6
expectBytes函数需要您指定一个字节解码器,如果您想要立即将字节转换为代码中更有意义的内容,则此函数非常有用。
然而,如果您希望在不必要克隆或读取字节的情况下保留原始的Bytes,您可能会发现expectBytesResponse更加实用。它的签名如下:
expectBytesResponse : (Result x a -> msg) -> (Response Bytes -> Result x a) -> Expect msg

该函数不需要解码器作为输入。它需要两个函数,这些函数能让你将响应字节(Response Bytes)翻译为一个 Result,另一个函数(第一个参数)则可将该 Result 转化为一个 Msg。通过每一步,你都可以保留原始的 Bytes 引用,在稍后的时间里随心所欲地处理。

但是,你将需要手动处理更多的 HTTP 响应情况,但至少你可以完全掌控如何处理你的数据字节。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接