Http.get中的Elm字节解码

问题描述 投票:1回答:1

我对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/[email protected]/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)
byte elm decoding
1个回答
0
投票

expectBytes函数要求您指定一个字节解码器,如果您立即想将字节转换为代码中更有意义的内容,则此方法很有用。

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

expectBytesResponse

这不将解码器作为输入。它有两个函数可让您将expectBytesResponse : (Result x a -> msg) -> (Response Bytes -> Result x a) -> Expect msg 转换为Response Bytes,另一个函数(第一个参数)可将Result转换为Result。通过上述每个步骤,您都可以保留原始的Msg参考,以供日后使用。

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

© www.soinside.com 2019 - 2024. All rights reserved.