byte - 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)
解决方案
该expectBytes
函数要求您指定字节解码器,如果您想立即将字节转换为代码中更有意义的内容,这将非常有用。
但是,如果您想Bytes
在应用程序中保留原始数据,而此时不必克隆或以其他方式读取字节,您可能会发现expectBytesResponse
更有用。它有签名:
expectBytesResponse : (Result x a -> msg) -> (Response Bytes -> Result x a) -> Expect msg
这不将解码器作为输入。它有两个函数可以让您转换Response Bytes
为 aResult
和另一个函数(第一个参数),它可以让您将其Result
转换为Msg
. 通过这些步骤中的每一个,您都可以保留原始Bytes
参考,以便以后随意使用。
但是,您将不得不手动处理更多 HTTP 响应场景,但至少您可以完全控制如何处理您的字节。
推荐阅读
- java - 为什么在这个基本的 Spring 应用程序中没有调用函数?
- android - TextView Drawable 兼容返回 null
- swift - SwiftUI:如何根据 Picker 的值更新 ForEach 循环的范围
- python - 如何从列表中提取值并将其存储为字典(键值对)?
- android - 如何使用 FCM 插件正确注册插件
- json - 如何计算反应表中的列
- sql - 排除包含除数字以外的任何内容的行
- java - Spring Cloud Contract 未执行 @Before
- android - Android:在调试中使用 RecyclerView 在初始滚动时出现 Jank
- c# - Unity C# 相机出现问题,相机变白