I am trying to make my Ionic app upload an image that was selected by the user. I read several tutorials, however i didn't manage to make it work. I want the app to run in the browser, therefore I didn't implement a solution running on mobile platforms only.
My angular component sends a post request to a server where the following php-script is hosted and an "uploads" folder is created as specified. But everytime I want to upload my file I get the "There was an error uploading the file, please try again!" message specified in my PHP-Script.
I think I might be send the data in the wrong format, however could figure out what to do.
Any ideas what my problem could be?
<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
header('Content-type: application/json');
$data = ['success' => true, 'message' => 'Upload and move success'];
echo json_encode( $data );
} else{
header('Content-type: application/json');
$data = ['success' => false, 'message' => 'There was an error uploading the file, please try again!'];
echo json_encode( $data );
}
?>
And here is my Typescript code in my component:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-erledigt-modal',
templateUrl: './erledigt-modal.component.html',
styleUrls: ['./erledigt-modal.component.scss'],
})
export class ErledigtModalComponent implements OnInit {
constructor(private http: HttpClient) { }
selectedFile = null;
ngOnInit() {
}
onFileChanged(event) {
this.selectedFile = <File>event.target.files[0]
}
onUpload() {
const uploadData = new FormData();
uploadData.append('image', this.selectedFile, this.selectedFile.name);
this.http.post('https://...MyAPI.../upload.php', uploadData).subscribe(res => {
console.log(res);
});
}
}
I also tried the following POST-request without success:
this.http.post('https://...MyAPI.../upload.php', this.selectedFile).subscribe(res => {
console.log(res);
});
}
My HTML looks simply like this:
<input type="file" (change)="onFileChanged($event)">
<button type="button" (click)="onUpload()">Upload</button>
I found the solution....
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path))and
do not work together because the name I used in the formdata is 'image' and the PHP script expects 'file'.. so changing 'image' to 'file' was the solution...