1

How do I download file in Fable? Let's say I have a CSV data and I want to save it on my machine.

I tried using ts2fable with the Download.js. However, it creates just an interface:

// ts2fable 0.6.1
module rec Download

open Fable.Import

type [<AllowNullLiteral>] IExports =
    abstract downloadUrl: title: string * url: string -> unit
    abstract downloadBlob: title: string * blob: Browser.Blob -> unit
    abstract downloadText: title: string * content: string -> unit

I think there is a way directly import a .js module

let download = Fable.Core.JsInterop.importMember "../src/download.js"

But it doesn't look nice and elegant.

P_O
  • 435
  • 6
  • 16

1 Answers1

2

you can use the import function in Fable in order to use the same syntax in JavaScript.

So in your case, it would give something like:

// If the file is in your src folder
let download : Download.IExports = import "*" "./path/to/download.js"

// If you use npm to manage the library
let download : Download.IExports = import "*" "download.js"

And you can use the code like that:

let anchor = Browser.document.createElement("a") :?> Browser.HTMLAnchorElement
anchor.innerText <- "Test download"

anchor.onclick <- fun _ ->
    download.downloadText("test.txt", "Hello, this is the content of the file.")

Browser.document.body.appendChild(anchor)
|> ignore

For information, I tested the code under Firefox, Chrome, and Safari. It works for Chrome and Safari but nothing happens under Firefox. I don't know if this is a limitation of Firefox or the library.

Maxime Mangel
  • 1,906
  • 16
  • 18