Skip to content

How do I upload a file from the client?

Fable makes it quick and easy to upload files from the client.


1. Create a File

Create a file in the client project named FileUpload.fs somewhere before the Index.fs file and insert the following:

module FileUpload

open Feliz
open Fable.Core.JsInterop

2. File Event Handler

Then, add the following. The reader.onload block will be executed once we select and confirm a file to be uploaded. Read the FileReader docs to find out more.

let handleFileEvent onLoad (fileEvent:Browser.Types.Event) =
    let files:Browser.Types.FileList = !!fileEvent.target?files
    if files.length > 0 then
        let reader = Browser.Dom.FileReader.Create()
        reader.onload <- (fun _ -> reader.result |> unbox |> onLoad)
        reader.readAsArrayBuffer(files.[0])

3. Create the UI Element

Insert the following block of code at the end of FileUpload.fs. This function will create a UI element to be used to upload files.

let createFileUpload onLoad =
    Html.input [ 
        prop.type' "file"
        prop.label "Choose a file"
        prop.onChange (handleFileEvent onLoad)
    ]

4. Use the UI Element

Having followed all these steps, you can now use the createFileUpload function in Index.fs to create the UI element for uploading files.

FileUpload.createFileUpload (HandleFile >> dispatch)

One thing to note is that HandleFile is a case of the discriminated union type Msg that's in Index.fs.

type Msg =
    // other messages
    | HandleFile of Browser.Types.Event

let update msg model =
    match msg with
    //other messages
    | HandleFile event ->
    // do what you need with the file