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>
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.
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.
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.
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)
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With