从Filepond对象实例获取数据

时间:2019-01-25 15:32:17

标签: javascript reactjs file filepond

我在React项目中有一个提交表单,我在这里使用filepond API,因此用户可以将文件提交到表单

到目前为止,我只是使用从文档中提取的标准FilePond组件。

   <FilePond ref={ref => this.pond = ref}
                      allowMultiple={true} 
                      maxFiles={4} 
                      oninit={() => this.handleInit() }
                      onupdatefiles={(fileItems) => {
                          // Set current file objects to this.state
                          this.setState({
                              files: fileItems.map(fileItem => fileItem.file)
                          });
                      }}>

                {/* Update current files  */}
                {this.state.files.map(file => (
                    <File key={file} src={file} origin="local" 
                 />
                ))}

            </FilePond>

我正在将整个请求发送到Java中的后端REST服务器,因此我希望将信息类型,数据(以base64编码)和文件扩展名一起发送。

我是通过在请求中创建对象数组来实现的

  result: this.state.files.map(file => ({
            "file": this.findFileTypeHandler(file.name), 
            "data": this.encodeFileHandler(file)
        }))
    }

在我的encodeFileHandler中,我需要一种将数据转换为base64的方法,但在文件对象上看不到具有原始数据的属性。

是否可以访问它,或者有人可以使用更好的选择吗?

here is an example of the properties available on the object

2 个答案:

答案 0 :(得分:1)

尝试File encode plugin进行文件缓冲,它完全可以满足您的需求:

  

...它会将已删除的文件编码为base64字符串,并将该字符串存储为JSON字符串在隐藏的输入字段中。它使用JSON字符串,因此还可以添加文件大小,类型,名称和元数据。

用法(反应):
导入插件代码:

import FilePondPluginFileEncode from 'filepond-plugin-file-encode';

注册插件:

registerPlugin(FilePondPluginFileEncode);

更多详细信息here

答案 1 :(得分:1)

对于正在寻找从 FilePond 对象中获取 file blob 的方法的人来说,这对我有用。我像这样保留了对 FilePond 对象的引用:

pond = FilePond.create(
    document.querySelector('#file'), {
        allowMultiple: true,
        instantUpload: false,
        allowProcess: false
    });

然后使用 pond.getFiles() 方法获取 FilePond 文件的对象。这与 blob 文件对象不同,

<块引用>

FilePond 文件不同于 JavaScript 文件或 Blob。 FilePond 文件是 JavaScript 文件对象的包装器。 FilePond docs

但是,您可以使用 file 属性来获取这样的 blob 文件,

pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
    // todo get file blob with pondFiles[i].file
}