DEV Community

loading...

How To Download A File using ReasonML

abdisalan_js profile image Abdisalan Originally published at abdisalan.com Updated on ・1 min read

This article was originally published on my blog


The solution is to use javascript. For now.

Some of the methods we use here, such as Blob aren't yet implemented in ReasonML (or I just couldn't find them), so we need to put some javascript into our ReasonML code using interop.

Here's a working version using codesandbox you can play with.

https://codesandbox.io/s/how-to-download-arbitrary-data-reasonml-yoxyg

Javascript Interop

In ReasonML, you can wrap javascript with [%bs.raw {| ...code goes here... |}] and it is accessible to the Reason code.

How Downloading works

First, we create a blob (Binary Large OBject) with our text MIME type.

var content = new Blob(["I AM TEXT"], {type: "text/plain"});
Enter fullscreen mode Exit fullscreen mode

Then we create an object url that can reference the data in our Blob and we add this url to the anchor tag.

document.getElementById("download")
        .setAttribute("href", window.URL.createObjectURL(content));
Enter fullscreen mode Exit fullscreen mode

Lastly, we set the download attribute so that we can name our downloaded file.

document.getElementById("download")
        .setAttribute("download", fileName);
Enter fullscreen mode Exit fullscreen mode

In conclusion, the link to the blob causes the browser to download the file, and gives it our name.

All the code together:

index.html

<html>
<body>
    <a href="" id="download">Download File</a>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

index.re

let setupDownload = [%bs.raw
    {|
    function() {
        var fileName = "data.txt";
        var content = new Blob(["I AM TEXT"], {type: "text/plain"});

        document.getElementById("download")
                .setAttribute("href", window.URL.createObjectURL(content));

        document.getElementById("download")
                .setAttribute("download", fileName);
    }
    |}
];

setupDownload();
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app