Created
November 8, 2020 21:14
-
-
Save sporto/8e863d7214cffd4ad3ebb302ec8de0ad to your computer and use it in GitHub Desktop.
Download a file in Elm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (main) | |
import Browser | |
import Bytes exposing (Bytes) | |
import File.Download as Download | |
import Html exposing (Html, button, div, text) | |
import Html.Events exposing (onClick) | |
import Http | |
type alias Model = | |
{} | |
init : () -> ( Model, Cmd Msg ) | |
init _ = | |
( {}, Cmd.none ) | |
type Msg | |
= Download | |
| Downloaded (Result Http.Error Bytes) | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
Download -> | |
( model | |
, download | |
) | |
Downloaded result -> | |
case result of | |
Err _ -> | |
( model, Cmd.none ) | |
Ok content -> | |
( model | |
, saveFile content | |
) | |
download = | |
Http.request | |
{ method = "GET" | |
, headers = | |
[] | |
, url = url | |
, body = Http.emptyBody | |
, expect = Http.expectBytesResponse Downloaded (resolve Ok) | |
, timeout = Nothing | |
, tracker = Nothing | |
} | |
url = | |
"https://ellie-app.com/r/workspace?token=SFMyNTY.g3QAAAACZAAEZGF0YW0AAAAkZTY5OGU2NjktZDI4ZC00NzhiLTgyNDktMWI2N2ExMzAyNzAwZAAGc2lnbmVkbgYAegOqqXUB.UGtqoBWw6-t-d4i6YGx8Yy-kkgPcEv_eBZOuqPXYw4Y&elmVersion=0.19.1" | |
resolve : (body -> Result String a) -> Http.Response body -> Result Http.Error a | |
resolve toResult response = | |
case response of | |
Http.BadUrl_ url_ -> | |
Err (Http.BadUrl url_) | |
Http.Timeout_ -> | |
Err Http.Timeout | |
Http.NetworkError_ -> | |
Err Http.NetworkError | |
Http.BadStatus_ metadata _ -> | |
Err (Http.BadStatus metadata.statusCode) | |
Http.GoodStatus_ _ body -> | |
Result.mapError Http.BadBody (toResult body) | |
saveFile : Bytes -> Cmd msg | |
saveFile content = | |
Download.bytes "file.txt" "application/txt" content | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ button [ onClick Download ] [ text "Download" ] | |
] | |
main : Program () Model Msg | |
main = | |
Browser.element | |
{ init = init | |
, view = view | |
, update = update | |
, subscriptions = always Sub.none | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment