I'm new in ReactJS and my backend is laravel and I have problem regarding inserting multiple files to the database, however if i use only the single upload (inserting one file to the database it's working for me.).
PROBLEM: regarding inserting multiple files in the database.
GOAL: To insert multiple files to the database
I have here
FORMDATA:
const formData = new FormData();
formData.append('myFile', this.state.image);
RESPONSE:
axios.post('/api/save_gallery_album_image', formData).then(response => {
console.log(response);
}).catch(error => (error.response));
OnChange:
handleChangeImage(e){
this.setState({
image:e.target.files[0]
})
// console.log(e.target.files);
}
JSX:
<label>Image</label>
<div className="custom-file">
<input type="file"
name="image"
multiple
onChange={this.handleChangeImage}
className="custom-file-input form-control"
accept="image/x-png,image/gif,image/jpeg"
id="file_selected"/>
<label className="custom-file-label" htmlFor="validatedCustomFile">Choose file...</label>
</div>
Server side Controller:
public function save_gallery_album_image(Request $request)
{
$multiple_gallery_file_upload = $request->file('myFile');
$titleValue = $request->get('titleValue');
$pageValue = $request->get('pageValue');
$now = new DateTime();
if($request->hasFile('myFile'))
{
foreach($multiple_gallery_file_upload as $myfiles)
{
$uniqueid=uniqid();
$original_name=$request->file('myFile')->getClientOriginalName();
$size=$request->file('myFile')->getSize();
$extension=$request->file('myFile')->getClientOriginalExtension();
$name=$uniqueid.'.'.$extension;
$path=$request->file('myFile')->storeAs('public',$name);
DB::insert('INSERT INTO album_category (cid,image,created_at) VALUES (?,?,?) ',[
$titleValue,
$name,
$now
]);
}
return response()->json('Input Saved');
}
}
<input>elements name attribute needs to be formatted like this:<input name="images[]" multiple/>then you can access it in laravel:$images = $request->file('images'); if($request->has('images'){//loop throughforeach($images as $image){$image->}