DEV Community

Abdisalan
Abdisalan

Posted on • Edited on • Originally published at abdisalan.com

1 1

How To Download A File using ReasonML

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay