Commands for downloading files.
SECURITY NOTE: Browsers require that all downloads are initiated by a user event. So rather than allowing malicious sites to put files on your computer however they please, the user at least have to click a button first. As a result, the following commands only work when they are triggered by some user event.
Download a String as a file. Maybe you markdown editor in the browser,
and you want to provide a button to download markdown files:
import File.Download as Download
save : String -> Cmd msg
save markdown =
Download.string "draft.md" "text/markdown" markdownSo the arguments are file name, MIME type, and then the file content. In this case is is markdown, but it could be any string information.
Download some Bytes as a file. Maybe you are creating custom images,
and you want a button to download them as PNG files. After using
elm/bytes to generate the file content, you can download it like
this:
import Bytes exposing (Bytes)
import File.Download as Download
savePng : Bytes -> Cmd msg
savePng bytes =
Download.bytes "frog.png" "image/png" bytesSo the arguments are file name, MIME type, and then the file content. With the
ability to build any byte sequence you want with elm/bytes, you can
create .zip files, .jpg files, or whatever else you might need!
Download a file from a URL. So you could download a GIF about math like this or this with the following code:
The downloaded file will use whatever name the server suggests.
Note: There exists a way to suggest an alternate name, but it seems to work only for same origin downloads. It should be more reliable to set the
Content-Dispositionheader on the server side. Adding a header likeContent-Disposition: attachment; filename="triangle.gif"should do it.