我正在尝试使用Fable-Elmish和React Helpers上传文件 . 但是,当我选择一个文件到可以使用Fetch发送到服务器的东西时,我无法弄清楚如何转换表单事件 . 这是观点:
R.input [
ClassName "input-control"
Type "file"
OnChange (fun x -> FileUploaded x.target |> dispatch )
] []
我的更新功能的相应部分:
| FileUploaded file ->
model, Cmd.ofPromise postCsv file FetchSuccess FetchFailure
以及使用fetch调用api的函数:
let postData input =
let formData = FormData.Create()
formData.append("file.csv", input?files)
let defaultProps =
[ RequestProperties.Method HttpMethod.POST
; RequestProperties.Body (formData |> unbox)]
promise {
return! Fable.PowerPack.Fetch.fetch ("/api/data") defaultProps
}
如何将React.FormEvent转换为fetch需要的BodyInit?
4 回答
您需要创建一个新的FormData对象并将文件附加到该对象 .
let formData = FormData.createNew formData.append("file", file.[0])
然后将您的调用更改为postRecord以传递formData而不是file . 您需要获取对其进行编码,但您只是传递原始文件数组 .
至少这是我对fetch example关于上传文件的理解 . 另外,发布记录看起来不对我,你可以使用"post"方法吗? postRecord意味着它期待一种记录类型 .
我认为
Fetch.postRecord
是你的问题,它将Content-Type
Headers 设置为application/json
,当it should bemultipart/form-data
时 .你需要使用原始的fetch API,而不是powerpack包装器,like this .
在测试代码后,检查
ev.target?value
显示该事件只是抓取所选文件的名称 .postRecord
似乎用于将json发送到 endpoints . 你想要移植:https://medium.com/ecmastack/uploading-files-with-react-js-and-node-js-e7e6b707f4ef,你想要做什么 .事实证明我没有正确使用FileList API . 这是post方法的工作解决方案: