I cannot upload multiple images from **angular ** using a Laravel api, when I try to upload these images from Postman it works, but when I do it from my frontend it failed.
I need a help please, any idea !!
this is my api function:
public function storeImages(Request $request)
{
if($request->hasFile('images')) {
$data = [];
foreach($request->file('images') as $image)
{
$Imagename = $image->getClientOriginalName();
$image->move(public_path('/images'), $Imagename);
$data[] = $Imagename;
}
$file = new ImageAnnonce($request->input()) ;
$file->annonceId = $request->annonceId;
$file->image_name = json_encode($data);
$file->save();
return response()->json($data);
}
else {
return response()->json(['message' => 'failed']);
}
}
This is the html
<form (ngSubmit)="saveMultipleImage()">
<input
class="form-control"
type="file"
id="images"
name="images[]"
(change)="onSelectFile($event)"
multiple
/>
<button type="submit" class="btn btn-primary float-right" id="publier-btn">
submite
</button>
</form>
file.ts
saveMultipleImage(){
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
var formdata = new FormData();
//formdata.append('annonceId', '2' );
for (let i = 0; i < this.length; i++)
{
formdata.append('images', this.docs[i].name );
//console.log('name -->', this.docs[i].name );
}
this.http.post('http://127.0.0.1:8000/api/storeImages', formdata,{headers: headers}).subscribe(res => {
console.log(res);
});
}
docs:any;
length:any;
onSelectFile(event)
{
this.docs = <File>event.target.files;
this.length = <File>event.target.files.length;
}
It returns always
{message: "failed"}
Can you try by removing headers.append('Content-Type', 'multipart/form-data'); from your header? Also, is your console log giving you the correct logs?
Lastly, what's the datatype of docs variable? Try making it of type File
docs: File[] = [];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.