0

I've built a form framework that handles the redux form and wraps the fields to use material ui component inputs.

I had the form framework working at sending files when I wrapped the submit data using formData();

This worked well - but when I have tried to use the field array in redux forms and appended the file field to it -- it comes back to the server as a key - representing the field -- but the contents is listed as an "[object object]" -- like the data has been converted into a string and can't be decoded.

--

if(this.props.returnAsFormData){
  const formData = new FormData();

  for (var field in data) {
    if(typeof data[field] !== "object"){
      formData.append(field, data[field]);
    }
    else{
      // loop through object
      //console.log(field, data[field]);
      if(data[field]){
        for (var i = 0; i < data[field].length; i++) {
          formData.append(field, data[field][i]);
        }
      }
    }
  }

  data = formData;
}


this.props.submitHandler(data);

--

I've tried to see if I can just touch the file field only to convert it from a FileList to a binary - but I can't seem to do the same thing that formData did. I've tried something like this - but its just not coming out as a Binary file as before.

function create_binary(file, callback) {
    var reader = new FileReader();
    reader.onload = function() { callback(reader.result) };
    reader.readAsBinaryString(file);
}   

x

for (var field in data) {
  if(data[field] && typeof data[field] === "object"){
    var file = data[field][0];
    create_binary(file, function(binary) {
      data[field] = binary;
    });
  }
}  
The Old County
  • 89
  • 13
  • 59
  • 129

1 Answers1

0

this fixed my problem --- looping through the nested json object was needed.

https://redux-form.com/8.3.0/examples/fieldarrays/ Redux Form field arrays -- makes the json more complex as the children fields are in an array object - so if there is a file field in the children - the json output would need to be made in FormData.

Convert JS Object to form data

function buildFormData(formData, data, parentKey) {
  if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
    Object.keys(data).forEach(key => {
      buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
    });
  } else {
    const value = data == null ? '' : data;

    formData.append(parentKey, value);
  }
}

function jsonToFormData(data) {
  const formData = new FormData();
  
  buildFormData(formData, data);
  
  return formData;
}

const my_data = {
  num: 1,
  falseBool: false,
  trueBool: true,
  empty: '',
  und: undefined,
  nullable: null,
  date: new Date(),
  name: 'str',
  another_object: {
    name: 'my_name',
    value: 'whatever'
  },
  array: [
    {
      key1: {
        name: 'key1'
      }
    }
  ]
};

jsonToFormData(my_data)
The Old County
  • 89
  • 13
  • 59
  • 129