Thanks, I was waiting for this! My use case is to load a png image via http and to display it with an <img>
tag as a base64 encoded url.
Unfortunately, it doesn’t work – fromBytes
returns Nothing
.
I reproduced it with a random image from the web (http://pngimagesfree.com/NATURE/Tree/tree_png_24.png). Just put the image near Main.elm and run it with elm-reactor (and you should see Nothing
in the console):
module Main exposing (main)
import Base64
import Browser
import Bytes exposing (Bytes)
import Http
type alias Model =
()
type Msg
= GotImage (Result Http.Error Bytes)
main : Program () Model Msg
main =
Browser.document
{ init = \() -> init
, subscriptions = \_ -> Sub.none
, view = \_ -> { title = "", body = [] }
, update = update
}
init : ( Model, Cmd Msg )
init =
( ()
, Http.get
{ url = "/tree_png_24.png"
, expect =
Http.expectBytesResponse GotImage <|
\response ->
case response of
Http.BadUrl_ url ->
Err (Http.BadUrl url)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ metadata body ->
Err (Http.BadStatus metadata.statusCode)
Http.GoodStatus_ metadata body ->
Ok body
}
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GotImage (Ok bytes) ->
let
_ =
Debug.log "base64" (Base64.fromBytes bytes)
in
( ()
, Cmd.none
)
GotImage (Err err) ->
let
_ =
Debug.log "err" err
in
( ()
, Cmd.none
)