In Elm, how can I access a file on my local drive?
For example, I need to access the file:
c:\MyFolder\somefile.txt
(I'm assuming you're targeting the browser and not Node. If you want Node support, here is the documentation for it's fs
module. The high-level usage will be similar to what I'm describing below for browsers.)
There is not (yet) an Elm-only API for this, so you'll have to use ports. This article is very helpful, I will adapt its example.
In short, you have to use File
and FileReader
API (caniuse.com), and on load of the file send the data to Elm through port. (In my example below, Elm will get a GetFile {name : String, content : String}
message for every file submitted.) Here is a working example in Ellie.
Msg:
type Msg
= GetFile File
type alias File =
{ name : String
, content : String
}
Port:
port getFile : (File -> msg) -> Sub msg
(don't forget port module
instead of module
on top of the Elm source)
Subscription:
subscriptions : Model -> Sub Msg
subscriptions model =
getFile GetFile
HTML file input:
<input type="file" id="files" name="files[]" multiple />
JS (the main part!):
<script>
var app = Elm.Main.fullscreen();
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
app.ports.getFile.send({name: theFile.name, content: e.target.result});
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
EDIT: this example only accepts images. If you don't want that, remove the
if (!f.type.match('image.*')) {
continue;
}
part and do something different in the viewFile
function (ie. don't try to interpret the content
data as an image src
).
Elm is now able open files as of 0.19.
Steps are as follows:
Please refer to this thread on Elm discourse, which includes this example on Ellie app
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With