In my project using Angular 8 for the front end and Laravel 5.8 for the backend, I encountered an issue with uploading photos. I found guidance in this tutorial from ACADE MIND.
Here is my template code :
<input *ngIf="photoEdit" enctype="multipart/form-data" type="file" (change)="onFileChanged($event)" #fileInput>
<button *ngIf="photoEdit" class="btn btn-xs btn-danger" (click)="onUpload()"> Save</button>
<button class="btn btn-small btn-primary" (click)="editPhoto()">Change Photo</button>
Within the following method :
public onFileChanged(event) {
this.selectedFile = event.target.files[0];
console.log(this.selectedFile);
}
The file selection is successfully logged in the console.
The onUpload() method :
onUpload() {
const uploadData = new FormData();
uploadData.append('photo', this.selectedFile,this.selectedFile.name);
this.http.post('http://127.0.0.1:8000/api/photo/upload', uploadData, this.authService.getHeader())
.subscribe(event => {
console.log(event);
});
}
getHeader()
public getHeader() {
var token: string;
token = "bearer" + this.getToken();
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': token
});
let options = { headers: headers };
return options;
}
I am encountering the following error message:
error : "Call to a member function extension() on null"
When uploading a photo using Postman, everything works fine. The server logs show:
[Tue Nov 26 07:34:27 2019] Log In
[Tue Nov 26 07:34:34 2019] POST /api/photo/upload HTTP/1.1
...
Server Side function:
public function upload(request $request)
{
error_log($request);
$extension = $request->file('photo')->extension();
if ($request->hasFile('photo')) {
error_log("FILE");
}
$fileName = "logedUserName";
$fileName = $fileName . "." . $extension;
$savedPhotoName = $request->photo->storeAs('public', $fileName);
return $savedPhotoName;
}