mpizenberg / elm-file / FileValue

Files


type alias File =
{ value : Json.Decode.Value
, name : String
, mime : String
, size : Basics.Int
, lastModified : Time.Posix 
}

Represents an uploaded file with its metadata.

The file is store as its raw JavaScript value. If needed, it is possible to convert it to the File type defined in elm/file simply by using the decoder defined there on the value field here.

decoder : Json.Decode.Decoder File

Decode File values.

encode : File -> Json.Decode.Value

Encode a File.

Load files with an input

hiddenInputSingle : String -> List String -> (File -> msg) -> Html msg

A hidden file input to load a single file. To use it, add a visible label linked to this input by its id.

type Msg
    = LoadData File

view _ =
    div []
        [ hiddenInputSingle "TheFileInput" [ "text/csv" ] LoadData
        , label [ for "TheFileInput" ] [ text "click to load data" ]
        ]

hiddenInputMultiple : String -> List String -> (File -> List File -> msg) -> Html msg

A hidden file input to load multiple files. To use it, add a visible label linked to this input by its id.

type Msg
    = LoadImages File (List File)

view _ =
    div []
        [ hiddenInputMultiple "TheFileInput" [ "image/*" ] LoadImages
        , label [ for "TheFileInput" ] [ text "click to load the images" ]
        ]

Drop files

onDrop : DropConfig msg -> List (Html.Attribute msg)

Create Html attributes for a file dropping area.

type Msg
    = DragOver File (List File)
    | Drop File (List File)
    | DragLeave

dropConfig =
    { onOver = DragOver
    , onDrop = Drop
    , onLeave = Just { id = "FileDropArea", msg = DragLeave }
    }

view _ =
    div (FileValue.onDrop dropConfig)
        [ text "Drop files here" ]


type alias DropConfig msg =
{ onOver : File -> List File -> msg
, onDrop : File -> List File -> msg
, onLeave : Maybe { id : String
, msg : msg } 
}

Configuration of a file drop target. The onOver, onDrop and onLeave record entries of DropConfig correspond respectively to the Html dragover, drop and dragleave events.

The Html dragenter and dragleave events generally are unreliable because they bubble up from children items and do not behave consistently with borders.

Since the dragover event can usually replace the dragenter event, we do not provide a config entry for dragenter. Beware though that the dragover event will trigger multiple times while the mouse is moving on the drop area.

If you really want to track dragleave events, you need to also provide a unique id that will be used to identify the event original target.