首页 > 解决方案 > Http.get 中的 Elm 字节解码

问题描述

我对 elm 很陌生,并且遇到了一个问题,即用我的后端数据填充我的模型。我目前能够向服务器发出获取请求,该请求返回一个字节 [](数据是任何类型的图像、音频或视频),当仅通过例如 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
module GeneralTypes exposing (..)

import Bytes exposing (Bytes)
import Http

type Msg = GetThumbnail (Result Http.Error Bytes)

标签: byteelmdecoding

解决方案


expectBytes函数要求您指定字节解码器,如果您想立即将字节转换为代码中更有意义的内容,这将非常有用。

但是,如果您想Bytes在应用程序中保留原始数据,而此时不必克隆或以其他方式读取字节,您可能会发现expectBytesResponse更有用。它有签名:

expectBytesResponse : (Result x a -> msg) -> (Response Bytes -> Result x a) -> Expect msg

这不将解码器作为输入。它有两个函数可以让您转换Response Bytes为 aResult和另一个函数(第一个参数),它可以让您将其Result转换为Msg. 通过这些步骤中的每一个,您都可以保留原始Bytes参考,以便以后随意使用。

但是,您将不得不手动处理更多 HTTP 响应场景,但至少您可以完全控制如何处理您的字节。


推荐阅读