'How to upload and move image in angular using laravel web API?
student-api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class StudentAPIService {
constructor(private httpClient: HttpClient) { }
registerStudent(data){
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
return this.httpClient.post('http://localhost/angular_laravel/laravelAPI/addStudent', data, { headers: headers });
}
}
add.component.html
<form class="form-horizontal" #fm="ngForm">
<fieldset>
<div class="control-group">
<label class="control-label" for="registration">Student Registration</label><br/>
<hr/>
</div>
<div class="control-group">
<label class="control-label" for="fname">Full Name</label>
<div class="controls">
<input type="text" id="fname" name="fname" placeholder="" class="input-xlarge" ngModel>
</div>
</div>
<div class="control-group">
<label class="control-label" for="photo">Image</label>
<div class="controls">
<input type="file" id="photo" name="photo" placeholder="" ngModel>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-success" (click)="registration(fm.value)">Register</button>
</div>
</div>
</fieldset>
</form>
add.component.ts
import { Component, OnInit } from '@angular/core';
import { StudentAPIService } from 'src/app/services/student-api.service';
import { Student } from 'src/app/model/student';
@Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {
public res: any;
constructor( private studentAPI: StudentAPIService ) { }
ngOnInit(): void {
}
registration(fm){
this.studentAPI.registerStudent(fm).subscribe(res=>{
console.log(res);
});
}
}
Laravel Controller - StudentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
use DB;
class StudentController extends Controller
{
public function store(Request $request) {
if ($request->hasFile('photo'))
{
$file = $request->file('photo');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').'-'.$filename;
$file->move(public_path('img'), $picture);
$student = new Student([
'student_name' => $request->get('fname'),
'photo' => $filename
]);
$student->save();
return response()->json('Successfully register');
}
}
}
In the above code I want to upload and move image using angular via laravel web API. Here, What happen when I click on button then try to print dd($request->hasFile('photo')) in StudentController.php then it return false. I don't know where I am doing wrong. Please help me.
Thank You
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
