javascript - 使用 Fable 获取文件输入内容

标签 javascript html f# fable-f#

我看过 simple ways使用 HTML5 File API 从 JavaScript 中输入的文件中读取内容。

这是我的 view 方法,在一个小型 fable-arch 应用程序中:

let view model =
    div [
        attribute "class" "files-form"
    ] [
        form [
            attribute "enctype" "multipart/form-data"
            attribute "action" "/feed"
            attribute "method" "post"
        ] [
            label [ attribute "for" "x_train" ] [ text "Training Features" ]
            input [
                attribute "id" "x_train"
                attribute "type" "file"
                onInput (fun e -> SetTrainingFeaturesFile (unbox e?target?value)) 
            ]
        ]
        model |> sprintf "%A" |> text
    ]
  • 是否有直接从 F# 捕获文件内容的简单方法?
  • 完成此任务所需的最少互操作代码是多少?

最佳答案

I couldn't find a way to not write plain JavaScript mainly because I couldn't import/instantiate FileReader from Fable. If someone can do it, then the solution can probably improve.

读取文件是异步的。这意味着 View 应该生成延迟的模型更新。由于这只能在模型更新函数中完成,我不得不在内部转发一个 JavaScript 文件句柄。

纯 JavaScript 只是一个导出 hack

// file interops.js, can I get rid of this?
export var getReader = function() { return new FileReader(); }

在 View 中

// view code
input [
    attribute "id" "x_train"
    attribute "type" "file"
    onInput (fun e -> FromFile (SetField, e?target?files?(0)))
]

因此该消息实际上是“带文件内容的延迟消息”。这是操作和更新代码:

type Action =
    | SetField of string
    | FromFile of (string -> Action) * obj

let update model action =
    match action with
    | SetField content ->
        { model with Field = content}, []
    | FromFile (setAction, file) ->
        let delayedAction h =
            let getReader = importMember "../src/interops.js"
            let reader = getReader()
            reader?onload <- (fun () ->  h <| setAction !!reader?result)
            reader?readAsText file |> ignore
        model, delayedAction |> toActionList

FromFile 是一项复杂的操作,因为我想用它来设置多个字段。如果您只需要一个,您可以将其设为 of obj

关于javascript - 使用 Fable 获取文件输入内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41419120/

相关文章:

javascript - Angularjs 和 Requirejs : Error: [$injector:modulerr]

javascript - 使导航项与褪色图像分开

html - 将 Div 缩放到内容

php - INNER JOIN + SELECT 特定列

html - 我已经在 1920x1080 显示器中为我的网站制作了响应式设计

javascript - WordPress 强制脚本在插件之后加载

javascript - 以 Angular 添加样式

.net - 为什么这个同步运行的异步 sleep 会挂起?

enums - 如何在枚举中保留值类型

f# - 有没有办法让 F# 保持参数的类型通用?