gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:46:10 35 4
gpt4 key购买 nike

我看过 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com