Kim Carlo Kim Carlo - 16 days ago 6
Javascript Question

Dropzone JS only uploading one file

I am using DropzoneJS in one of my projects. I am using laravel to process the backend for file upload. I used a div in my form and add the dropzone class to it.

<div class="col-md-12 dropzone file_upload"></div>


it works fine but only one file is being uploaded. I want it to upload multiple files simultaneously.

I already set the
parallelUploads
option in my dropzone configuration to
10
and the
maxFiles
option to
10
also.

here is my code for the dropzone configuration:

$("div.file_upload").dropzone({
url: upload,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
autoProcessQueue: true,
addRemoveLinks: true,
uploadMultiple: true,
params: {
"model_id": 1,
"user_id" : 2
},
maxFiles: 10,
parallelUploads: 10,


});


below is my code for the backend

Controller.php

public function uploadPhoto(Request $request){

foreach ($request->file('file') as $file) {

$filename = uniqid().'.'.$file->getClientOriginalExtension();
$file->move('images/booking', $filename);

//save details to db
$photo= new InspectionPhotos();
$photo->inspection_id = $request['inspection_id'];
$photo->product_id = $request['product_id'];
$photo->photo_path = $filename;
if($photo->save()){
return response()->json([
'message' => 'OK'
]);
}

}

}

Answer

The problem is the return statement in Controller.php.

After the first file is saved, the function uploadPhoto() returns, never getting to save the second file.

Wrap the save() function in try-catch and return error status in the catch block, and handle the errors in front-end appropriately. You might also want to have $file->move() in try-catch as it might throw errors as well.

Finally, move the return statement out of foreach to return success status.

Glad the answer helped you, cheers!