TransWikia.com

The contents of the input file are always undefined when I print formData, why? ReactJS

Stack Overflow Asked by bmalbusca on February 13, 2021

I’m trying to upload a file (may be multiple as well) but after uploading to the input component, the only thing I saw after appended to FormData() is undefined. But, if I print an object info or info[‘data’], it will appear.


fileHandler =(input) => {

    const formData = new FormData();
    const info = this.createDataBlob();

    for (let i = 0; i < input.files.length; i++) {

      formData.append(input.files[i].name,input.files[i])
      info['data'].push(this.createFileHeader(input.files[i].name))

    }

    formData.append('content.json',info)
    console.log( 'Processed Data:', formData['content.json'])
}

//used as content info for the API endpoint - saves all file dicts
createDataBlob = () => ({'data':[] , 'storage': 'neo4j-driver' })

 //returns a dict used to describe the file
createFileHeader = (name, description='') => ({ 'name': name, 'text': description})


render(){
  return (
    <Form>
      <input
        label="Custom file input"
        accept=".shp, .csv"
        type="file"
        id="input"
        multiple
        onChange={ (event) => this.fileHandler(event.target)}
      />
    </Form>
  );

  }

}

One Answer

You can not console.log FormData entries this way, this is a special object.

Quote from Mozilla website:

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.

However, if you would like to log out these values, you could use entries() to access them this way.

const fileHandler = (event) => {
        const formData = new FormData();

        for (let i = 0; i < event.target.files.length; i++) {
            formData.append(event.target.files[i].name, event.target.files[i].type);
        }

        // use values this way (entries)
        for (var key of formData.entries()) {
            console.log(`${key[0]}, ${key[1]}`);
        }
    }

    return (
        <div>
            <input
                label="Custom file input"
                accept=".shp, .csv"
                type="file"
                id="input"
                multiple
                onChange={fileHandler}
            />
        </div>
    );

Also, I made a little change for your onChange in this example, using target in the handler, but your method was also fine I think.

Correct answer by axtck on February 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP