Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Abdisalan
Abdisalan

Posted on • Edited on • Originally published atabdisalan.com

     

How To Download A File using ReasonML

This article was originally published onmy blog


The solution is to use javascript. For now.

Some of the methods we use here, such asBlob 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.

varcontent=newBlob(["I AM TEXT"],{type:"text/plain"});
Enter fullscreen modeExit 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 modeExit fullscreen mode

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

document.getElementById("download").setAttribute("download",fileName);
Enter fullscreen modeExit 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><ahref=""id="download">Download File</a></body></html>
Enter fullscreen modeExit 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 modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A software engineer just trying to gain and share knowledge with everyone.
  • Location
    Boulder
  • Education
    BS in Computer Science
  • Work
    Software Engineer at Google
  • Joined

More fromAbdisalan

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp