Get data from filepond object instance

I have a submit form in my React project, where I'm using the filepond API, so users can submit files to the form

I'm just using the standard FilePond component taken from the documentation so far.

   <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>

I'm sending the entire request to a backend REST server in java, and therefore I want to send along to types of information, the data (base64 encoded), and the extension of the file.

I do this by creating an array of objects in my request

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

in my encodeFileHandler, I need a way to convert the data to base64, but I can't see a property, that has the raw data, on the file object.

Is there a way to access it, or does anybody have a better alternative I could use?

here is an example of the properties available on the object

Upvotes: 5

Views: 12876

Answers (2)

rez
rez

Reputation: 2077

For whose who are looking for a way to get file blob out of a FilePond object, here is what worked for me. I kept a reference to FilePond object like this:

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

And then used pond.getFiles() method to get FilePond files' object. This is different from blob file objects,

A FilePond File is not the same a JavaScript File or Blob. The FilePond File is a wrapper around a JavaScript file object. FilePond docs

However, you can use file property to get the blob file like this,

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

Upvotes: 6

Braca
Braca

Reputation: 2805

Try File encode plugin for filepond, it's doing exactly what you need:

... it encodes a dropped file as a base64 string and stores the string in a hidden input field as a JSON string. It uses a JSON string so it can also add the file size, type, name and metadata.

Usage(React):
Import the plugin code:

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

Register the plugin:

registerPlugin(FilePondPluginFileEncode);

More details here

Upvotes: 5

Related Questions