我对 elm 还很陌生,并且遇到了使用后端数据填充模型的问题。我目前可以向服务器发出 get 请求,该请求返回一个 byte[] (数据是任何类型的图像、音频或视频),当仅通过 Html.img 显示此数据时,它可以正常工作。当我尝试使用 Http.get (src: https: //package.elm-lang.org/packages/elm/http/latest/Http)来填充我的模型时,它需要解码器。问题是,Bytes.Decode.bytes 需要一个 Int 来知道需要解码多少字节。所以我的问题是:有没有什么方法可以访问字节宽度,同时仍然匹配 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
Run Code Online (Sandbox Code Playgroud)
module GeneralTypes exposing (..)
import Bytes exposing (Bytes)
import Http
type Msg = GetThumbnail (Result Http.Error Bytes)
Run Code Online (Sandbox Code Playgroud)
该expectBytes函数要求您指定一个字节解码器,如果您想立即将字节转换为代码中更有意义的内容,则该解码器非常有用。
但是,如果您希望Bytes在应用程序中保留原始数据,而不必此时克隆或以其他方式读取字节,您可能会发现expectBytesResponse更有用。它有签名:
expectBytesResponse : (Result x a -> msg) -> (Response Bytes -> Result x a) -> Expect msg
Run Code Online (Sandbox Code Playgroud)
这不采用解码器作为输入。它需要两个函数,可以让您将其转换Response Bytes为 a Result,另一个函数(第一个参数)可以让您将其转换Result为 a Msg。通过每个步骤,您都可以保留原始Bytes参考,以便以后随意使用。
然而,您将必须手动处理更多 HTTP 响应场景,但至少您可以完全控制如何处理您的字节。