0

In my Angular app, I'm trying to append a file, selected from a FileUpload control, to a FormData object:

fileUploadHandle(files) {    
    if (files && files.length > 0) {
      this.fileContentFormData = files[0];
    }
}

console.log('file content - ' + JSON.stringify(this.fileContentFormData));
form_data.append('file', this.fileContentFormData);
form_data.append('username', 'Chris');
console.log('form data - ' + JSON.stringify(form_data));

I know my file is being retrieved because when I run console.log('file content - ' + JSON.stringify(this.fileContentFormData)); this is displayed:

file content - {"file":{},"id":0,"icon":"doc","src":{"changingThisBreaksApplicationSecurity":"data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,UEsDBBQABgAIAAAAIQAJJIeCgQ="}}

However, when I run console.log('form data - ' + JSON.stringify(form_data)); even the 'username' key-value pair isn't even being displayed.

Can someone please tell me what I'm doing wrong when appending to this FormData object? Thanks a lot!

user9847788
  • 2,135
  • 5
  • 31
  • 79

1 Answers1

2

Previously, it was not possible to inspect a FormData object with your debugger. The latest versions of Chrome and Firefox now support FormData.entries() to inspect FormData.

// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

// Display the key/value pairs
for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); 
}

Please check this thread for the source.

ahbon
  • 502
  • 4
  • 19
  • Hi, I used this on my code like so: `var pair of form_data.entries()`, but I'm getting a compile error: Property 'entries' does not exist on type 'FormData'.ts(2339) – user9847788 May 03 '19 at 08:48
  • The `entries`method is not supported by all browsers. Check a possible solution here: https://stackoverflow.com/questions/50677868/error-ts2339-property-entries-does-not-exist-on-type-formdata – ahbon May 03 '19 at 08:53
  • This error is in VS Code – user9847788 May 03 '19 at 09:08
  • I've used `alert(JSON.stringify(form_data));` & {} is being printed so there is nothing in form_data. I'm not sure how this answers my question. – user9847788 May 03 '19 at 09:18
  • I also tried `form_data.append('testAdd', 'testValue');` to see if I could add something to the formData, but it's still printing an empty object – user9847788 May 03 '19 at 09:20
  • Just create a fake interface for `FormData` that contains a `entries()` method as it's done in the other thread I gave you. It will correct your typescript error. – ahbon May 03 '19 at 09:29