This is the basic file upload I am trying using angular and php. When I choose the file in UI, I can see the file details.
But, when I execute it I am getting empty array as response in network tab.
What might be the issue?
I have checked php.ini file and everything seems fine to me.
(I also tried to print using print_r ($_FILES); It gives empty array.)
I have attached Angular(.html, .ts) and .php file here:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
echo ($_POST['file']);
?>
<form [formGroup]="myForm" (ngSubmit)="submit()" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="file">File</label>
<input
formControlName="file"
id="file"
type="file"
class="form-control"
(change)="onFileChange($event)">
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
myForm = new FormGroup({
file: new FormControl('', [Validators.required]),
fileSource: new FormControl('', [Validators.required])
});
constructor(private http: HttpClient) { }
ngOnInit(): void {
}
get f(){
return this.myForm.controls;
}
onFileChange(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
console.log('File', file);
this.myForm.get('fileSource').setValue(file);
}
}
submit(){
const formData = new FormData();
formData.append('file', this.myForm.get('fileSource').value);
this.http.post('http://localhost/]api/document/SaveContact.php', formData)
.subscribe(res => {
console.log(res);
// alert('Uploaded Successfully.');
})
}
}
$_POST['file']will never work for a file upload, it'll always be in$_FILESif it's there. Does the network tool show the file being successfully sent in the request payload?http://localhost/]api/document/SaveContact.phpthis.myForm.get('fileSource').valueis file path but FormData.append second parameter is actual value to send with request. usethis.myForm.get('fileSource').files[0]as File or create FormData byconst formData = new FormData(this.myForm)ifthis.myFormis HTMLFormElement.