Reputation: 1204
I'm trying to upload file in Angular 4 and send it to php with another data like text, when I use var_dumb() to read the data the File Object empty.
My post.component.html
:
<a class="upload-photo-item">
<input type="file" class="Upload-photo" accept="image/*" ngf-max-size="2MB" (change)="handleInputChange($event)"/>
<i class="fa fa-tags olymp-computer-icon" aria-hidden="true"></i>
<h6>Upload Photo</h6>
<span>Browse your computer.</span>
</a>
And this is handleInputChange
function:
post = new PostObject();
image: File;
handleInputChange(event) {
console.log(event);
this.image = event.target.files[0];
var pattern = /image-*/;
if (!this.image.type.match(pattern)) {
console.log('File is not an image');
return;
}
this.post.postPhoto = this.image;
console.log('image :' + this.image);
}
Everything until now is perfect, I can see my Object file in console, Now here is the problem:
My post.php
:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
exit;
The API response with array(0) like this:
It can be solved by base64
but this is not an option for me, any ideas please?
Upvotes: 2
Views: 3254
Reputation: 716
Hope this helps, how to send formdata in Angular 2+:
import {HttpClient, HttpHeaders} from '@angular/common/http';
...
constructor(private http: HttpClient) {}
...
test() {
const formData = new FormData();
formData.append('data', JSON.stringify({
test: 'test'
}));
formData.append('file', file);
const headers = new HttpHeaders().set('Content-Type', []);
// responseType 'text' is necessary for IE
return this.http.post(url, formData, {
headers,
responseType: 'text'
});
}
Upvotes: 2