Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

Webapi and input files

$
0
0

I’ve adapted my code (which parses a CSV file) to your requirements.

module File = {
  type t
}

module FileReader = {
  type t

  type event = [
    | #load
    | #abort
  ]

  @new external make: unit => t = "FileReader"

  @send external readAsDataURL: (t, File.t) => unit = "readAsDataURL"

  @send
  external addEventListener: (t, event, unit => unit) => unit =
    "addEventListener"

  @get external result: t => string = "result"
}

@react.component
let make = () => {
  <label>
    <input
      accept="csv"
      name="csvImport"
      id="csvImport"
      onChange={ev => {
        let input = ev->JsxEvent.Form.currentTarget
        let files: array<File.t> = input["files"]
        files->Array.forEach(f => {
          let reader = FileReader.make()
          reader->FileReader.addEventListener(#load, () => {
            Console.log(FileReader.result(reader))
          })
          reader->FileReader.readAsDataURL(f)
        })
      }}
      type_="file"
    />
    {"Import statement from a CSV file"->React.string}
  </label>
}

The compiled JavaScript code as seen in this playground link reads fine (but I haven’t run it).

I haven’t used rescript-webapi (if that’s what you’ve referred to in your question) though. You can make a judgment call on whether to integrate the above code with WebApi’s types and bindings or not.


Viewing all articles
Browse latest Browse all 2592

Trending Articles