【问题标题】:Read forms data in javascript/react在 javascript/react 中读取表单数据
【发布时间】:2020-06-23 04:03:37
【问题描述】:

我正在使用 react 库:https://react-jsonschema-form.readthedocs.io/en/latest/ 从 json 文件创建表单,并上传本地文件。

我正在使用live demo 中的“文件”示例来加载本地文件

图书馆正在成功地做哪些事情。我已经验证了这一点,因为我创建了一个文本文件,其内容是字符串“test”,当我加载文件时

在 chrome 控制台中,我得到以下响应:

{schema: {…}, uiSchema: {…}, idSchema: {…}, formData: {…}, edit: false, …}
additionalMetaSchemas: undefined
edit: false
errorSchema: {}
errors: []
formData: {file: "data:text/plain;name=Nuevo%20documento%20de%20texto.txt;base64,dGVzdA=="}
idSchema: {$id: "root", file: {…}}
schema: {title: "Files", type: "object", properties: {…}}
uiSchema: {}
__proto__: Object

文件的所有细节,如文件名和内容都在变量formData中 例如。编码后的内容“dGVzdA==”是“test”,这意味着它确实读取了文件。

formData: {file: "data:text/plain;name=Nuevo%20documento%20de%20texto.txt;base64,dGVzdA=="}

我的问题是我无法从那里访问数据,我尝试输入:

FormData

这给了我结果:

ƒ FormData() { [native code] } 

但没有别的。我也试过

FormData["file"] 和 "file" 但这些都不起作用

我也尝试过:

document.getElementById("root");

但这只会给我 html 代码,而不是我上传的文件的内容。

【问题讨论】:

  • from there 是什么意思?另外,您提到FormDataAPI)但输出是formData ????
  • 我的回答解决了你的问题吗?

标签: javascript reactjs


【解决方案1】:

一个非常简单的方法是使用fetch api

fetch(formData)
    .then(res => res.blob())
    .then(blob => blob.text())
    .then(console.log)

但唯一的问题是它可能违反内容安全策略 (CSP)。

如果是这样,您可以使用 custom function 来解析 dataURL 并像这样使用它:

function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);

    // create a view into the buffer
    var ia = new Uint8Array(ab);

    // set the bytes of the buffer to the correct values
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    var blob = new Blob([ab], {type: mimeString});
    return blob;
}

dataURItoBlob(formData).text().then(console.log)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 2019-05-05
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多