I was to trying to upload images via my frontend (React) to my laravel rest API, but I am unable to do it.
I obtained the file input data from the input via fileInputElement.files[fileInputElement is just a placeolder I am doing it via triggered event object and yes I am taking multiple files]. I logged it to check if it's obtained (and yes it is) after that I appended it to form data and sent it to the server but the server cannot find the images in my request.
Below is the code.
React file upload codes
let formData = new FormData();
formData.append('name', this.state.name);
formData.append('category_id', this.state.category_id);
for(let i = 0; i < this.state.images.length; i++){
let image = this.state.images[i];
formData.append(`images[${i}]`, image);
}
axios.post('/api/products', formData, { headers: {'Content-Type': 'multipart/form-data'} })
Do note that yes the files are present in my this.state.images I logged them to check it. Laravel codes to the file
$images = [];
foreach ($request->files('images') as $image) {
$name = uniqid();
$fullname = $name.'.'.$image->getClientOriginalExtenstion();
$filepath = "/photos/products/$fullname";
array_push($images, $filepath);
Image::make($image)->save($filepath);
}
$data = [
'images' => $images,
'category_id' => $request->category_id,
'name' => $request->name
];
$product = Product::create($data);
I cannot get the images from images array from the request, it returns null.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire