Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular form data won't append

I am trying to upload files with angular 6. However, I can't seem to append my formData(). Alittle help. Thank you.

home.component.ts

export class HomeComponent implements OnInit {
  selectedFile: File = null;
constructor(
private _route: ActivatedRoute,
private _router: Router,
private _postService: PostService
) { }

ngOnInit() {}


onFileChanged(event) {
this.selectedFile = event.target.files[0]}

postImage() {
const uploadData = new FormData();
uploadData.append('myFile', this.selectedFile, this.selectedFile.name);
console.log(uploadData)
this._postService.postImage(uploadData)}}

home.component.html

<input style="display: none" type="file (change)="onFileChanged($event)" #fileInput>
<button (click)="fileInput.click()">Select File</button>
<button (click)="postImage()">Upload!</button>
like image 988
Jack G Avatar asked Aug 27 '18 02:08

Jack G


People also ask

How to append value in FormData?

append() The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

How to FormData append array?

To append array to FormData and send via Ajax with JavaScript, we can use the spread operator. const formData = new FormData(); const arr = ["this", "is", "an", "array"]; for (const a of arr) { formData. append("arr[]", a); } console.

How get all values from FormData?

getAll() The getAll() method of the FormData interface returns all the values associated with a given key from within a FormData object. Note: This method is available in Web Workers.


1 Answers

Try something like this:

DEMO

The file is already appended in formdata but You can not directly inspect form data :

onFileChanged(event) {

    let formData = new FormData();
    this.selectedFiles = event.target.files;
    this.currentFileUpload = this.selectedFiles.item(0);


    console.log(this.currentFileUpload)
    formData.append('file', this.currentFileUpload);

    formData.append('labelName', 'test');
    formData.append('formPart', 'test');
    console.log(JSON.stringify(formData))

   formData.forEach((value,key) => {
      console.log(key+" "+value)
    });
  }
like image 100
Akj Avatar answered Sep 27 '22 20:09

Akj